/**
 *  Copyright ©2008-2009 DRIVER-II Project All Rights Reserved
 *
 */
package eu.dnetlib.common.ws;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

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

import eu.dnetlib.common.interfaces.nh.INotificationListener;
import eu.dnetlib.common.interfaces.ws.IDriverService;
import eu.dnetlib.common.nh.Notification;

public abstract class DriverServiceImpl implements IDriverService {

	protected static final Log log = LogFactory.getLog(DriverServiceImpl.class);
	
	protected List<INotificationListener> listenerList = new ArrayList<INotificationListener>();
	protected INotificationListener notifier;
	protected String serviceVersion;
	
	public void addListener(INotificationListener aListener){
		log.debug("register listener");
		this.listenerList.add(aListener);
		this.notifier = aListener;
		log.debug(this.notifier.toString());
	}
	
	/* (non-Javadoc)
	 * @see org.driver.ws.DriverService#identify()
	 */
	public String identify() {
		log.debug("identify: " + serviceVersion);
		return serviceVersion;
	}

	/* (non-Javadoc)
	 * @see org.driver.ws.DriverService#notify(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	public boolean notify(String subscrId, String topic, String isId,
			String message) {
		boolean returnValue = false;
		log.debug("---- service got notification ----");
		log.debug("subscrId: " + subscrId);
		log.debug("topic " + topic);
		log.debug("isId " + isId);
		log.debug("msg: " + message);
		log.debug("____ now processing the notification ____");
		Notification notification = new Notification();
		notification.setDate(new Date());
		notification.setIsId(isId);
		notification.setMessage(message);
		notification.setSubscriptionId(subscrId);
		notification.setTopic(topic);
		log.debug("listSize of notificationListener list: " + listenerList.size());
		if (this.listenerList.size() == 0){
			if (this.notifier == null){
				log.debug("listener is null");
			}else{
				log.debug("processing by listener");
				returnValue = this.notifier.processNotification(notification);
			}
		}
		for (Iterator<INotificationListener> iter = this.listenerList.iterator(); iter.hasNext();){
			log.debug("process by listener");
			returnValue = iter.next().processNotification(notification);
		}
		return returnValue;
	}
	
	/**
	 * @return the notifier
	 */
	public INotificationListener getNotifier() {
		return notifier;
	}

	/**
	 * @param notifier the notifier to set
	 */
	public void setNotifier(INotificationListener notifier) {
		this.notifier = notifier;
	}

	public String getServiceVersion() {
		return serviceVersion;
	}

	public void setServiceVersion(String serviceVersion) {
		this.serviceVersion = serviceVersion;
	}


}
