package eu.dnetlib.data.mdstore.modular.action;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;

import eu.dnetlib.data.mdstore.MDStoreServiceException;
import eu.dnetlib.data.mdstore.modular.connector.MDStoreDao;
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;

/**
 * The Class AbstractMDStoreAction.
 */
public abstract class AbstractMDStoreAction implements BlackboardServerAction<MDStoreActions> {

	@Resource
	private UniqueServiceLocator serviceLocator;

	/** The dao. */
	private MDStoreDao dao;

	/** The executor. */
	private final Executor executor = Executors.newCachedThreadPool();

	/** Logger */
	private static final Log log = LogFactory.getLog(AbstractMDStoreAction.class);

	private static final ClassPathResource mdstoreServiceStatusTemplate = new ClassPathResource(
			"/eu/dnetlib/data/mdstore/modular/mdstoreServiceStatusTemplate.xml.st");

	/**
	 * Execute async.
	 * 
	 * @param handler
	 *            the handler
	 * @param job
	 *            the job
	 * @throws MDStoreServiceException
	 *             the MD store service exception
	 */
	protected abstract void executeAsync(final BlackboardServerHandler handler, final BlackboardJob job) throws MDStoreServiceException;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction#execute(eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler,
	 * eu.dnetlib.enabling.tools.blackboard.BlackboardJob)
	 */
	@Override
	public void execute(final BlackboardServerHandler handler, final BlackboardJob job) {
		executor.execute(new Runnable() {

			@Override
			public void run() {
				try {
					handler.ongoing(job);
					executeAsync(handler, job);
				} catch (MDStoreServiceException e) {
					handler.failed(job, e);
				}
			}
		});
	}

	protected void completeWithSuccess(final BlackboardServerHandler handler, final BlackboardJob job) {
		// Don't change this synchronization rule
		synchronized (this) {
			updateMDStoreServiceProfile(job);
			handler.done(job);
		}
	}

	protected void completeWithFail(final BlackboardServerHandler handler, final BlackboardJob job, final Throwable e) {
		// Don't change this synchronization rule
		synchronized (this) {
			updateMDStoreServiceProfile(job);
			handler.failed(job, e);
		}
	}

	private void updateMDStoreServiceProfile(final BlackboardJob job) {
		final String id = job.getServiceId();

		log.info("Updating mdstore service profile status, id: " + id);
		try {
			final StringTemplate st = new StringTemplate(IOUtils.toString(mdstoreServiceStatusTemplate.getInputStream()));
			st.setAttribute("status", dao.getDBStatus());
			serviceLocator.getService(ISRegistryService.class).updateProfileNode(id, "//STATUS", st.toString());
		} catch (Exception e) {
			log.error("Error upadating profile " + id, e);
		}
	}

	/**
	 * Gets the dao.
	 * 
	 * @return the dao
	 */
	public MDStoreDao getDao() {
		return dao;
	}

	/**
	 * Sets the dao.
	 * 
	 * @param dao
	 *            the new dao
	 */
	public void setDao(final MDStoreDao dao) {
		this.dao = dao;
	}

}
