package eu.dnetlib.enabling.is.sn;

import javax.xml.ws.WebServiceFeature;
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.common.rmi.BaseService;

/**
 * This is a basic notification invoker which calls dnet1.0 compatible notify() methods.
 *
 * @author marko
 *
 */
public class NotificationInvokerImpl implements NotificationInvoker {
	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(NotificationInvokerImpl.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * invocation logger.
	 */
	private NotificationInvocationLogger invocationLogger;

	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.enabling.is.sn.NotificationInvoker#send(javax.xml.ws.wsaddressing.W3CEndpointReference,
	 *      eu.dnetlib.enabling.is.sn.NotificationMessage, int)
	 */
	@Override
	public void send(final W3CEndpointReference destination, final NotificationMessage message, final int timeout) {
		final BaseService service = destination.getPort(BaseService.class, new WebServiceFeature[] {});
		log.info("phisically sending notification: " + message.getTopic());

		final NotificationInvocationLogger.Entry logEntry = invocationLogger.startLogging(destination, message);
		logEntry.ongoing();

		try {
			service.notify(message.getSubscriptionId(), message.getTopic(), message.getResourceId(), message.getBody());
			logEntry.success();
		} catch (final Throwable e) { // NOPMD
			log.debug("notification error", e);
			logEntry.failure(e);
		}
	}

	public NotificationInvocationLogger getInvocationLogger() {
		return invocationLogger;
	}

	@Required
	public void setInvocationLogger(final NotificationInvocationLogger invocationLogger) {
		this.invocationLogger = invocationLogger;
	}

}
