package eu.dnetlib.enabling.is.sn;

import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;

import eu.dnetlib.enabling.is.sn.resourcestate.ResourceStateNotificationDetector;
import eu.dnetlib.enabling.tools.DOMOpaqueResource;
import eu.dnetlib.enabling.tools.OpaqueResource;
import eu.dnetlib.xml.database.LoggingTrigger;

/**
 * This trigger generates notification events for the subscription notification layer. 
 * 
 * @author marko
 *
 */
public class NotificationTriggerImpl extends LoggingTrigger {
	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(NotificationTriggerImpl.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * notification detector to notify on events.
	 */
	private ResourceStateNotificationDetector<OpaqueResource> detector;

	/** 
	 * {@inheritDoc}
	 * @see eu.dnetlib.xml.database.LoggingTrigger#created(java.lang.String, java.lang.String, org.w3c.dom.Document)
	 */
	@Override
	public void created(final String file, final String collection, final Document newDoc) {
		super.created(file, collection, newDoc);
		try {
			getDetector().resourceCreated(new DOMOpaqueResource(newDoc));
		} catch (XPathExpressionException e) {
			log.fatal("cannot detect notification because of xpath error; notification possibly missed", e);
		}
	}

	/** 
	 * {@inheritDoc}
	 * @see eu.dnetlib.xml.database.LoggingTrigger#deleted(java.lang.String, java.lang.String, org.w3c.dom.Document)
	 */
	@Override
	public void deleted(final String file, final String collection, final Document oldDoc) {
		super.deleted(file, collection, oldDoc);
		try {
			getDetector().resourceDeleted(new DOMOpaqueResource(oldDoc));
		} catch (XPathExpressionException e) {
			log.fatal("cannot detect notification because of xpath error; notification possibly missed", e);
		}
	}

	/** 
	 * {@inheritDoc}
	 * @see eu.dnetlib.xml.database.LoggingTrigger#updated(java.lang.String, java.lang.String, org.w3c.dom.Document, org.w3c.dom.Document)
	 */
	@Override
	public void updated(final String file, final String collection, final Document oldDoc, final Document newDoc) {
		super.updated(file, collection, oldDoc, newDoc);
		try {
			getDetector().resourceUpdated(new DOMOpaqueResource(oldDoc), new DOMOpaqueResource(newDoc));
		} catch (XPathExpressionException e) {
			log.fatal("cannot detect notification because of xpath error; notification possibly missed", e);
		}
	}
	
	public ResourceStateNotificationDetector<OpaqueResource> getDetector() {
		return detector;
	}

	public void setDetector(final ResourceStateNotificationDetector<OpaqueResource> detector) {
		this.detector = detector;
	}
}
