
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.smack.XMPPConnection;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smackx.pubsub.Item;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import com.beem.project.beem.smack.pep.PepSubManager;
import com.beem.project.beem.smack.pep.PEPListener;

public class AvatarManager {

    private PepSubManager 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 PepSubManager(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, String node, List<Item> items) {

             Log.d("AvatarMgr", "Received pep event ");
	     Item i = items.get(0);
	     if (i instanceof PayloadItem) {
		 PayloadItem<PacketExtension> pi = (PayloadItem<PacketExtension>) i;
		 PacketExtension ex = pi.getPayload();
		 if (ex instanceof AvatarMetadataExtension) {
		     Log.d("AvatarMgr", "Received avatar meta");
		     AvatarMetadataExtension ext = (AvatarMetadataExtension) ex;
		     Info info = selectAvatar(ext.getInfos());
		     if (!mCache.contains(info.getId()))
			 downloadAvatar(from, info);
		 }
	     }
	}
    }

}
