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

import java.util.HashMap;
import java.util.Map;

import javax.xml.ws.wsaddressing.W3CEndpointReference;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.ClassPathResource;

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

import eu.dnetlib.enabling.resultset.XSLTMappedResultSetFactory;
import eu.dnetlib.enabling.resultset.client.utils.EPRUtils;
import eu.dnetlib.msro.rmi.MSROException;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;

public class ApplyXsltJobNode extends SimpleJobNode {

	private String inputEprParam;
	private String outputEprParam;
	private String xsltClasspath;

	private XSLTMappedResultSetFactory xsltMappedResultSetFactory;

	@Override
	protected String execute(final NodeToken token) throws Exception {
		final String inputEpr = token.getEnv().getAttribute(inputEprParam);
		if ((inputEpr == null) || inputEpr.isEmpty()) throw new MSROException("InputEprParam (" + inputEprParam + ") not found in ENV");

		final Map<String, String> xsltParams = new HashMap<String, String>();

		for (String name : token.getFullEnv().getAttributeNames()) {
			xsltParams.put(name.replaceAll(":", "_"), token.getFullEnv().getAttribute(name));
		}
		for (String name : token.getEnv().getAttributeNames()) {
			xsltParams.put(name.replaceAll(":", "_"), token.getEnv().getAttribute(name));
		}

		xsltParams.putAll(parseJsonParameters(token));

		final W3CEndpointReference epr = xsltMappedResultSetFactory.createMappedResultSet(new EPRUtils().getEpr(inputEpr),
				(new ClassPathResource(xsltClasspath)), xsltParams);

		token.getEnv().setAttribute(outputEprParam, epr.toString());

		return Arc.DEFAULT_ARC;
	}

	public String getInputEprParam() {
		return inputEprParam;
	}

	public void setInputEprParam(final String inputEprParam) {
		this.inputEprParam = inputEprParam;
	}

	public String getOutputEprParam() {
		return outputEprParam;
	}

	public void setOutputEprParam(final String outputEprParam) {
		this.outputEprParam = outputEprParam;
	}

	public String getXsltClasspath() {
		return xsltClasspath;
	}

	public void setXsltClasspath(final String xsltClasspath) {
		this.xsltClasspath = xsltClasspath;
	}

	public XSLTMappedResultSetFactory getXsltMappedResultSetFactory() {
		return xsltMappedResultSetFactory;
	}

	@Required
	public void setXsltMappedResultSetFactory(final XSLTMappedResultSetFactory xsltMappedResultSetFactory) {
		this.xsltMappedResultSetFactory = xsltMappedResultSetFactory;
	}

}
