package eu.dnetlib.msro.workflows.nodes.repohi;

import java.util.Map;

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

import com.googlecode.sarasvati.Engine;
import com.googlecode.sarasvati.NodeToken;
import com.googlecode.sarasvati.env.Env;

import eu.dnetlib.data.objectstore.rmi.ObjectStoreService;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.msro.workflows.nodes.BlackboardJobNode;
import eu.dnetlib.msro.workflows.nodes.blackboard.BlackboardWorkflowJobListener;

public class CreateObjectStoreJobNode extends BlackboardJobNode {

	private static final Log log = LogFactory.getLog(CreateObjectStoreJobNode.class);

	private String interpretation;
	private String outputPrefix = "objectStore_";

	@Override
	protected String obtainServiceId(final NodeToken token) {
		return getServiceLocator().getServiceId(ObjectStoreService.class);
	}

	@Override
	protected void prepareJob(final BlackboardJob job, final NodeToken token) {
		log.info("preparing blackboard job for the creation of the objectStore ");
		String basePath  = token.getEnv().getAttribute("objectStoreBasePath");
		job.setAction("CREATE");
		job.getParameters().put("interpretation", interpretation);
		if (!StringUtils.isEmpty(basePath)) {
			job.getParameters().put("basePath", basePath);
		}
	}

	public String getInterpretation() {
		return interpretation;
	}

	public void setInterpretation(final String interpretation) {
		this.interpretation = interpretation;
	}

	public String getOutputPrefix() {
		return outputPrefix;
	}

	public void setOutputPrefix(final String outputPrefix) {
		this.outputPrefix = outputPrefix;
	}

	@Override
	protected BlackboardWorkflowJobListener generateBlackboardListener(final Engine engine, final NodeToken token) {
		return new BlackboardWorkflowJobListener(engine, token) {

			@Override
			protected void populateEnv(final Env env, final Map<String, String> responseParams) {

				env.setAttribute(getOutputPrefix() + "interpretation", interpretation);
				env.setAttribute(getOutputPrefix() + "id", responseParams.get("objectStoreId"));
			}
		};
	}

}
