package eu.dnetlib.data.objectstore.modular;

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

import eu.dnetlib.data.objectstore.modular.connector.ObjectStoreDao;
import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The Class AbstractObjectStoreAction.
 */
public abstract class AbstractObjectStoreAction implements BlackboardServerAction<ObjectStoreActions> {

	/**
	 * Logger
	 */
	private static final Log log = LogFactory.getLog(AbstractObjectStoreAction.class);
	private final Executor executor = Executors.newCachedThreadPool();
	/** The object store dao. */
	private ObjectStoreDao dao;

	protected abstract void executeAsync(final BlackboardServerHandler handler, final BlackboardJob job) throws ObjectStoreServiceException;

	@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 (ObjectStoreServiceException e) {
					handler.failed(job, e);
				}
			}
		});
	}

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

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

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

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

}
