
package com.beem.project.beem.smack.avatar;

import android.util.Log;

import com.beem.project.beem.smack.AvatarMetadataExtension;
import com.beem.project.beem.smack.AvatarMetadataExtension.Info;

import java.io.IOException;

import java.util.List;

import org.jivesoftware.smackx.packet.PEPEvent;
import org.jivesoftware.smackx.packet.PEPItem;
import org.jivesoftware.smackx.PEPListener;
import org.jivesoftware.smackx.PEPManager;
import org.jivesoftware.smack.XMPPConnection;

public class AvatarManager {

    private PEPManager mPep;
    private XMPPConnection mCon;
    private boolean mAutoDownload;
    private AvatarCache mCache;

    public AvatarManager(XMPPConnection con, AvatarCache cache, boolean autoDownload) {
	Log.d("AvatarMgr", "creation");
	mCon = con;
	mPep = new PEPManager(mCon);
	mAutoDownload = autoDownload;
	mCache = cache;
	if (mAutoDownload)
	    mPep.addPEPListener(new Listener());
    }

    public byte[] getAvatar(String avatarId) {
	try {
	    return mCache.get(avatarId);
	} catch (IOException e) {
	    return null;
	}
    }

    protected Info selectAvatar(List<Info> available) {
	return available.get(0);
    }

    private void downloadAvatar(String from, Info info) {
	try {
	    AvatarRetriever retriever = AvatarRetrieverFactory.getRetriever(mCon, from, info);
	    byte[] avatar = retriever.getAvatar();
	// TODO verifier le hash avant de stocker ?
	    mCache.put(info.getId(), avatar);
	} catch (IOException e) {
	    Log.d("AvatarMgr", "Error while downloading avatar", e);
	}
    }

    private class Listener implements PEPListener {
	@Override
	public void eventReceived(String from, PEPEvent event) {

	    PEPItem item = event.getPEPItem();
	    Log.d("AvatarMgr", "Received pep event " + item.toXML());
	    if (item instanceof AvatarMetadataExtension) {
		AvatarMetadataExtension ext = (AvatarMetadataExtension) item;
		Info info = selectAvatar(ext.getInfos());
		if (!mCache.contains(info.getId()))
		    downloadAvatar(from, info);
	    }
	}
    }

}
