package com.beem.project.beem.smack.pep;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketExtensionFilter;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.Item;
import org.jivesoftware.smackx.pubsub.ItemsExtension;
import org.jivesoftware.smackx.pubsub.EventElement;
import org.jivesoftware.smackx.pubsub.EventElementType;

import java.util.List;
import java.util.ArrayList;

public class PepSubManager extends PubSubManager {
    private List<PEPListener> pepListeners = new ArrayList<PEPListener>();
    private PacketFilter packetFilter = new PacketExtensionFilter("event", "http://jabber.org/protocol/pubsub#event");

    public PepSubManager(Connection connection) {
	super(connection);
	init(connection);
    }

    public PepSubManager(Connection connection, String toAddress) {
	super(connection, toAddress);
	init(connection);
    }

    public void addPEPListener(PEPListener listener) {
	if (!pepListeners.contains(listener))
	    pepListeners.add(listener);
    }

    public void removePEPListener(PEPListener listener) {
	pepListeners.remove(listener);
    }

    private void init(Connection con) {
	PacketListener packetListener = new PacketListener() {

	    @Override
	    public void processPacket(Packet packet) {
		EventElement e = (EventElement) packet.getExtension("event", "http://jabber.org/protocol/pubsub#event");
		if(e.getEventType() != EventElementType.items)
		    return;
		ItemsExtension it = (ItemsExtension) e.getEvent();
		if (it.getItemsElementType() != ItemsExtension.ItemsElementType.items)
		    return;
		List<Item> items = (List<Item>) it.getItems();
		firePEPListeners(packet.getFrom(), it.getNode(), items);
	    }
	};
	con.addPacketListener(packetListener, packetFilter);
    }

    private void firePEPListeners(String from, String node, List<Item> items) {
	for(PEPListener listener : pepListeners) {
	    listener.eventReceived(from, node, items);
	}
    }
}
