package org.buddycloud.channelserver.packetprocessor.message.event;

import java.util.Properties;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;
import org.buddycloud.channelserver.channel.ChannelManager;
import org.buddycloud.channelserver.db.exception.NodeStoreException;
import org.buddycloud.channelserver.pubsub.affiliation.Affiliations;
import org.dom4j.Element;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;

public class AffiliationProcessor extends AbstractMessageProcessor  {
 
	private JID jid;
	private Affiliations affiliation;

	private static final Logger logger = Logger
			.getLogger(AffiliationProcessor.class);

	public AffiliationProcessor(BlockingQueue<Packet> outQueue,
			Properties configuration, ChannelManager channelManager) {
		super(channelManager, configuration, outQueue);
	}

	@Override
	public void process(Message packet) throws Exception {
		message = packet;

		handleAffiliationElement();

		if (false == channelManager.isLocalNode(node)) {
			sendLocalNotifications();
		}
	}

	private void handleAffiliationElement() throws NodeStoreException {
		Element affiliationElement = message.getElement().element("event")
				.element("affiliation");
		if (null == affiliationElement) {
			return;
		}
		jid = new JID(affiliationElement.attributeValue("jid"));
		node = affiliationElement.attributeValue("node");
		affiliation = Affiliations.valueOf(affiliationElement
				.attributeValue("affiliation"));
		if (true == channelManager.isLocalNode(node)) {
			return;
		}
        storeNewAffiliation();
	}

	private void storeNewAffiliation() throws NodeStoreException {
		addRemoteNode();
		channelManager.setUserAffiliation(node, jid, affiliation);
	}

	private void addRemoteNode() {
        try { 
            channelManager.addRemoteNode(node); 
        } catch (NodeStoreException e) { 
        	logger.error(e);
        }
	}
}
@@ -550,20 +550,18 @@
 ocessor 
- 
 %7B%0A
- 
 %0A%09privat
@@ -1166,24 +1166,25 @@
  affiliation
+s
 Element = me
@@ -1223,16 +1223,92 @@
 t%22)%0A%09%09%09%09
+.element(%22affiliations%22);%0A%09%09Element affiliationElement = affiliationsElement
 .element
@@ -1446,32 +1446,33 @@
 de = affiliation
+s
 Element.attribut
@@ -1645,24 +1645,18 @@
 rn;%0A%09%09%7D%0A
-        
+%09%09
 storeNew
@@ -1856,151 +1856,123 @@
 e() 
-%7B%0A        try %7B %0A            channelManager.addRemoteNode(node); %0A        %7D catch (NodeStoreException e) %7B %0A        %09logger.error(e);%0A        %7D
+throws NodeStoreException %7B%0A%09%09if (false == channelManager.nodeExists(node))%0A%09%09%09%09channelManager.addRemoteNode(node);
 %0A%09%7D%0A

Fix processing of affiliation events