package eu.dnetlib.enabling.tools.blackboard;

import javax.annotation.Resource;
import javax.xml.bind.JAXBException;

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

import eu.dnetlib.miscutils.jaxb.JaxbFactory;

/**
 * This BB handler deletes completed (successful or unsuccessful) blackboard messages after dispatching. Job should be registered to only
 * one "deleting BB handler".
 * 
 * @author marko
 * 
 */
public class DeletingBlackboardNotificationHandler extends BlackboardNotificationHandler<BlackboardClientHandler> {

	/**
	 * Logger.
	 */
	private static final Log log = LogFactory.getLog(DeletingBlackboardNotificationHandler.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * blackboard message factory.
	 */
	@Resource(name = "blackboardMessageFactory")
	private JaxbFactory<BlackboardMessage> messageFactory;

	/**
	 * {@inheritDoc}
	 * 
	 * @see eu.dnetlib.enabling.tools.blackboard.BlackboardNotificationHandler#processJob(eu.dnetlib.enabling.tools.blackboard.BlackboardJob)
	 */
	@Override
	protected void processJob(final BlackboardJob job) {

		if (getListeners().containsKey(job.getId()) && job.isCompleted()) {
			if (log.isDebugEnabled()) {
				log.debug(serializeBlackBoardMessage(job));
			}
			getBlackboardHandler().delete(job);
		}
		super.processJob(job);
	}

	/**
	 * Helper method, serializes a Blackboard message using a blackboardMessageFactory.
	 * 
	 * @param job
	 * @return
	 */
	private String serializeBlackBoardMessage(final BlackboardJob job) {
		try {
			return getMessageFactory().serialize(job.getMessage());
		} catch (JAXBException e) {
			return "cannot serialize blackboard message: " + e.getMessage();
		}
	}

	public void setMessageFactory(final JaxbFactory<BlackboardMessage> messageFactory) {
		this.messageFactory = messageFactory;
	}

	public JaxbFactory<BlackboardMessage> getMessageFactory() {
		return messageFactory;
	}

}
