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

import javax.annotation.Resource;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.sarasvati.Arc;
import com.googlecode.sarasvati.NodeToken;

import eu.dnetlib.data.mdstore.MDStoreService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.msro.rmi.MSROException;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;

public class FetchMDStoreRecordsJobNode extends SimpleJobNode {

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

	@Resource
	private UniqueServiceLocator serviceLocator;

	private String mdId;
	@Deprecated
	/**
	 * @Deprecated: mdFormat not used by this job node.
	 */
	private String mdFormat;
	private String eprParam;

	@Override
	protected String execute(final NodeToken token) throws Exception {
		if (getMdId() == null) {
			setMdId(token.getEnv().getAttribute("mdId"));
		}
		if (getMdFormat() == null) {
			setMdFormat(token.getEnv().getAttribute("mdFormat"));
		}

		final Long dateFromFilter = token.getFullEnv().getAttribute("DateFromFilter", Long.class);

		if (dateFromFilter!= null) {
			log.info("From Filter activated, from: "+dateFromFilter);
		}

		final MDStoreService mdStoreService = serviceLocator.getService(MDStoreService.class, getMdId());
		int size = mdStoreService.size(getMdId());

		token.getEnv().setAttribute(WorkflowsConstants.MAIN_LOG_PREFIX + "sourceSize", size);
		log.info(String.format("getting MDRecords from: %s, sourceSize: %s", getMdId(), size));

		final String from = dateFromFilter != null ? "" + dateFromFilter : "";
		final W3CEndpointReference epr = mdStoreService.deliverMDRecords(getMdId(), from, "", "");
		if (epr == null) { throw new MSROException("unable to read MDRecords from: " + getMdId()); }
		token.getEnv().setAttribute(getEprParam(), epr.toString());
		return Arc.DEFAULT_ARC;
	}

	public String getMdId() {
		return mdId;
	}

	public void setMdId(final String mdId) {
		this.mdId = mdId;
	}

	@Deprecated
	/**
	 * Deprecated: MdFormat is not used by this job node
	 */
	public String getMdFormat() {
		return mdFormat;
	}
	@Deprecated
	/**
	 * Deprecated: MdFormat is not used by this job node
	 */
	public void setMdFormat(final String mdFormat) {
		this.mdFormat = mdFormat;
	}

	public String getEprParam() {
		return eprParam;
	}

	public void setEprParam(final String eprParam) {
		this.eprParam = eprParam;
	}
}
