package eu.dnetlib.enabling.hcm.sn;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.xml.ws.Endpoint;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.enabling.actions.SubscriptionAction;
import eu.dnetlib.enabling.is.sn.rmi.ISSNException;
import eu.dnetlib.enabling.is.sn.rmi.ISSNService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.soap.EndpointReferenceBuilder;

/**
 * This component takes care of subscribing the SubscriptionAction(s) to interesting events.
 * 
 * @author claudio
 * 
 */
public class HCMSubscriberImpl implements HCMSubscriber {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(HCMSubscriberImpl.class);

	/**
	 * notification endpoint (normally the msro service).
	 */
	private Endpoint endpoint;

	/**
	 * service locator.
	 */
	private UniqueServiceLocator serviceLocator;

	/**
	 * injected EPR builder.
	 */
	@Resource(name = "jaxwsEndpointReferenceBuilder")
	private EndpointReferenceBuilder<Endpoint> eprBuilder;

	/**
	 * subscription actions.
	 */
	private List<SubscriptionAction> actions;

	@PostConstruct
	public void printList() {
		log.info(getActions());
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @throws ISSNException
	 *             could happen
	 * @see eu.dnetlib.enabling.hcm.sn.HCMSubscriber#subscribeAll()
	 */
	@Override
	public void subscribeAll() throws ISSNException {

		final W3CEndpointReference endpointReference = eprBuilder
				.getEndpointReference(getEndpoint());

		if (getActions() != null) {
			for (final SubscriptionAction action : getActions()) {
				log.info("dynamically subscribing to "
						+ action.getTopicExpression());
				serviceLocator.getService(ISSNService.class, true).subscribe(endpointReference,
						action.getTopicExpression(), 0);
			}
		}
	}

	public void setEndpoint(final Endpoint endpoint) {
		this.endpoint = endpoint;
	}

	public Endpoint getEndpoint() {
		return endpoint;
	}

	public void setEprBuilder(
			final EndpointReferenceBuilder<Endpoint> eprBuilder) {
		this.eprBuilder = eprBuilder;
	}

	public EndpointReferenceBuilder<Endpoint> getEprBuilder() {
		return eprBuilder;
	}

	public List<SubscriptionAction> getActions() {
		return actions;
	}

	@Required
	public void setActions(final List<SubscriptionAction> actions) {
		this.actions = actions;
	}

	public UniqueServiceLocator getServiceLocator() {
		return serviceLocator;
	}

	@Required
	public void setServiceLocator(final UniqueServiceLocator serviceLocator) {
		this.serviceLocator = serviceLocator;
	}

}
