package eu.dnetlib.data.collective.manager.nh;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentException;

import eu.dnetlib.common.profile.Resource;
import eu.dnetlib.enabling.tools.blackboard.NotificationHandler;

/**
 * @author jochen
 *
 * @param <T> notification consumer
 */
public class AbstractServiceNotificationHandler<T extends INotificationConsumer> implements NotificationHandler{
	
	private static final Log log = LogFactory.getLog(AbstractServiceNotificationHandler.class);
	private List<String> topicPrefixList = new LinkedList<String>();
	private T notificationConsumer;
	
	/**
	 * @see eu.dnetlib.enabling.tools.blackboard.NotificationHandler#notified(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	public void notified(String subscrId, String topic, String rsId, String profile) {
		String[] splittedTopic = topic.split("[.]");
		if (splittedTopic.length < 2){throw new IllegalArgumentException("invalid topic:" + topic);};
		String topicPart = splittedTopic[0] + "." + splittedTopic[1];
		for (String topicPrefix: topicPrefixList){
			if (topicPrefix.startsWith(topicPart)){
				log.debug("notified topic: " + topicPart);
				Resource resource = null;
				try {
					resource = new Resource(profile);
				} catch (DocumentException e) {
					throw new IllegalStateException(e);
				}

				if (topic.startsWith("CREATE")){
					notificationConsumer.addResource(resource);
				}else if (topic.startsWith("DELETE")){
					notificationConsumer.removeResource(resource);
				}else if (topic.startsWith("UPDATE")){
					notificationConsumer.updateResource(resource);
				}
				return;
			}
		}
		log.debug("ignored topic: " + topicPart);
	}

	/**
	 * @param topicPrefixList the topicPrefixList to set
	 */
	public void setTopicPrefixes(List<String> topicPrefixList) {
		this.topicPrefixList = topicPrefixList;
	}
	/**
	 * @return the topicPrefixList
	 */
	public List<String> getTopicPrefixes() {
		return topicPrefixList;
	}
	
	/**
	 * @param aNotificationConsumer the notificationConsumer to set
	 */
	public void setNotificationConsumer(T aNotificationConsumer) {
		this.notificationConsumer = aNotificationConsumer;
	}
	
	/**
	 * @return the notification consumer
	 */
	public T getNotificationConsumer() {
		return this.notificationConsumer;
	}

}
