package eu.dnetlib.msro.workflows.sarasvati.loader;

import java.io.StringReader;

import javax.annotation.Resource;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.miscutils.functional.xml.ApplyXslt;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;

public class ProfileToSarasvatiConverter {

	@Resource
	private UniqueServiceLocator serviceLocator;

	private org.springframework.core.io.Resource xslt;

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

	public WfProfileDescriptor getSarasvatiWorkflow(final String id) throws DocumentException {
		final String s = getProfile(id);
		final Document doc = new SAXReader().read(new StringReader(s));
		final WfProfileDescriptor desc = new WfProfileDescriptor();
		desc.setName(doc.valueOf("//WORKFLOW_NAME"));
		desc.setType(doc.valueOf("//WORKFLOW_TYPE"));
		desc.setPriority(NumberUtils.toInt("//WORKFLOW_PRIORITY", WorkflowsConstants.DEFAULT_WF_PRIORITY));
		desc.setWorkflowXml(new ApplyXslt(xslt).evaluate(s));
		desc.setReady(doc.selectNodes("//PARAM[@required='true' and string-length(normalize-space(.)) = 0]").isEmpty());
		return desc;
	}

	public String getProfile(final String id) {
		try {
			return serviceLocator.getService(ISLookUpService.class).getResourceProfile(id);
		} catch (ISLookUpException e) {
			log.error("Error finding profile: " + id, e);
			return null;
		}
	}

	public org.springframework.core.io.Resource getXslt() {
		return xslt;
	}

	@Required
	public void setXslt(final org.springframework.core.io.Resource xslt) {
		this.xslt = xslt;
	}
}
