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

import java.io.IOException;
import java.io.StringWriter;
import javax.annotation.Resource;

import com.googlecode.sarasvati.Arc;
import com.googlecode.sarasvati.NodeToken;
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryException;
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants.WorkflowStatus;
import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;

public class RegisterMetaWfJobNode extends SimpleJobNode {

	@Resource
	private UniqueServiceLocator serviceLocator;
	private String adminEmail;

	private String wfName;

	@Override
	protected String execute(final NodeToken token) throws Exception {
		final String dsId = token.getFullEnv().getAttribute(WorkflowsConstants.DATAPROVIDER_ID);
		final String dsName = token.getFullEnv().getAttribute(WorkflowsConstants.DATAPROVIDER_NAME);
		final String ifaceId = token.getFullEnv().getAttribute(WorkflowsConstants.DATAPROVIDER_INTERFACE);

		final String metaWfId = registerDatasourceWorkflow(dsId, dsName, ifaceId);

		token.getFullEnv().setAttribute("META_WORKFLOW_ID", metaWfId);
		token.getFullEnv().setAttribute("META_WORKFLOW_STATUS", WorkflowStatus.ASSIGNED.toString());

		return Arc.DEFAULT_ARC;
	}

	public String registerDatasourceWorkflow(final String dsId, final String dsName, final String ifaceId) throws ISRegistryException, IOException {
		final StringWriter sw = new StringWriter();
		IOUtils.copy(getClass().getResourceAsStream("/eu/dnetlib/msro/workflows/templates/meta-workflow.xml.st"), sw);

		final StringTemplate st = new StringTemplate(sw.toString());
		st.setAttribute("dsId", dsId);
		st.setAttribute("ifaceId", ifaceId);
		st.setAttribute("dsName", StringEscapeUtils.escapeXml(dsName));
		st.setAttribute("section", "dataproviders");
		st.setAttribute("wfName", StringEscapeUtils.escapeXml(getWfName()));
		st.setAttribute("wfFamily", StringEscapeUtils.escapeXml(getWfName()));
		st.setAttribute("adminEmail", adminEmail);
		st.setAttribute("status", WorkflowStatus.ASSIGNED.toString());

		return serviceLocator.getService(ISRegistryService.class).registerProfile(st.toString());
	}

	public String getWfName() {
		return wfName;
	}

	public void setWfName(final String wfName) {
		this.wfName = wfName;
	}

	public String getAdminEmail() {
		return adminEmail;
	}

	public void setAdminEmail(final String adminEmail) {
		this.adminEmail = adminEmail;
	}
}
