package eu.dnetlib.functionality.modular.ui.workflows.util;

import java.io.StringReader;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

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.functionality.modular.ui.workflows.objects.AdvancedMetaWorkflowDescriptor;
import eu.dnetlib.functionality.modular.ui.workflows.objects.NodeInfo;
import eu.dnetlib.functionality.modular.ui.workflows.objects.NodeWithUserParams;
import eu.dnetlib.msro.workflows.util.WorkflowParam;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants.WorkflowStatus;

public class ISRegistryClient {

	@Resource
	private UniqueServiceLocator serviceLocator;

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

	public String registerProfile(final String profile) throws ISRegistryException {
		return serviceLocator.getService(ISRegistryService.class).registerProfile(profile);
	}

	public boolean updateSarasvatiWorkflow(final String wfId, final String profile, final NodeInfo info) throws Exception {
		final Document doc = new SAXReader().read(new StringReader(profile));

		final Node node = doc.selectSingleNode("//NODE[@name='" + info.getName() + "']");
		if (node == null) {
			log.error("Node " + info.getName() + " not found in profile " + profile);
		} else {
			node.selectSingleNode("./DESCRIPTION").setText(info.getDescription());
			for (WorkflowParam param : info.getParams()) {
				if (param.isUserParam()) {
					final String val = param.getValue() != null ? param.getValue() : "";
					node.selectSingleNode(".//PARAM[@name='" + param.getName() + "']").setText(val);
				}
			}
		}

		return serviceLocator.getService(ISRegistryService.class).updateProfile(wfId, doc.asXML(), doc.valueOf("//RESOURCE_TYPE/@value"));
	}

	public boolean updateSarasvatiWorkflow(final String wfId, final String profile, final List<NodeWithUserParams> list) throws Exception {
		final Document doc = new SAXReader().read(new StringReader(profile));
		for (NodeWithUserParams n : list) {
			final Node node = doc.selectSingleNode("//NODE[@name='" + n.getNode() + "']");
			if (node == null) {
				log.error("Node " + n.getNode() + " not found in profile " + profile);
			} else {
				for (WorkflowParam param : n.getParams()) {
					final String val = param.getValue() != null ? param.getValue() : "";
					final Node paramNode = node.selectSingleNode(".//PARAM[@name='" + param.getName() + "']");
					if (paramNode != null && paramNode.valueOf("@managedBy").equalsIgnoreCase("user")) {
						paramNode.setText(val);
					} else {
						log.debug("Node " + param.getName() + " not updated, because not found or not editable by user");
					}
				}
			}
		}

		return serviceLocator.getService(ISRegistryService.class).updateProfile(wfId, doc.asXML(), doc.valueOf("//RESOURCE_TYPE/@value"));
	}

	public boolean updateSarasvatiMetaWorkflow(final String wfId, final String profile, final AdvancedMetaWorkflowDescriptor info) throws Exception {
		final Document doc = new SAXReader().read(new StringReader(profile));

		doc.selectSingleNode("//METAWORKFLOW_NAME").setText(info.getName());
		if (info.getEmail() != null) {
			doc.selectSingleNode("//ADMIN_EMAIL").setText(info.getEmail());
		} else {
			doc.selectSingleNode("//ADMIN_EMAIL").setText("");
		}
		Node node = doc.selectSingleNode("//SCHEDULING");
		((Element) node).addAttribute("enabled", Boolean.toString(info.isScheduled()));
		node.selectSingleNode("./CRON").setText(info.getCronExpression());
		node.selectSingleNode("./MININTERVAL").setText(Integer.toString(info.getMinInterval()));

		return serviceLocator.getService(ISRegistryService.class).updateProfile(wfId, doc.asXML(), doc.valueOf("//RESOURCE_TYPE/@value"));
	}

	public void configureWorkflowStart(final String id, final String value) throws ISRegistryException {
		serviceLocator.getService(ISRegistryService.class).updateProfileNode(id, "//CONFIGURATION/@start", "'" + value + "'");
	}

	public void updateMetaWorkflowStatus(final String id, final WorkflowStatus status) throws ISRegistryException {
		serviceLocator.getService(ISRegistryService.class).updateProfileNode(id, "//CONFIGURATION/@status", "'" + status.toString() + "'");
	}

}
