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

import java.io.StringReader;
import java.io.StringWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;

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

import eu.dnetlib.enabling.datasources.common.Api;
import eu.dnetlib.enabling.datasources.common.Datasource;
import eu.dnetlib.enabling.datasources.common.LocalDatasourceManager;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
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;

public class DeleteMetaWfJobNode extends SimpleJobNode {

	private String metaWfId;

	@Autowired
	private UniqueServiceLocator serviceLocator;

	@Autowired
	private LocalDatasourceManager<Datasource<?, ?>, Api<?>> dsManager;

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

	@Override
	protected String execute(final NodeToken token) throws Exception {
		final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(metaWfId);
		final Document doc = new SAXReader().read(new StringReader(profile));

		final String dsId = doc.valueOf("//DATAPROVIDER/@id");
		final String dsName = doc.valueOf("//DATAPROVIDER/text()");
		final String ifaceId = doc.valueOf("//DATAPROVIDER/@interface");
		final String destroyWfId = doc.valueOf("//CONFIGURATION/@destroyWorkflow");

		log.info("Removing a MetaWf of dataprovider: " + dsId);

		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_ID, dsId);
		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_NAME, dsName);
		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_INTERFACE, ifaceId);

		final ISRegistryService registry = serviceLocator.getService(ISRegistryService.class);

		for (final Object o : doc.selectNodes("//WORKFLOW")) {
			final String wfId = ((Node) o).valueOf("@id");
			try {
				registry.deleteProfile(wfId);
				log.info(" - Deleted Workflow: " + wfId);
			} catch (final Exception e) {
				log.error(" - (ERR) Error deleting profile " + wfId);
			}
		}
		registry.deleteProfile(metaWfId);
		log.info(" - Deleted MetaWorkflow: " + metaWfId);

		registry.deleteProfile(destroyWfId);
		log.info(" - Deleted destroy workflow: " + destroyWfId);

		verifyDatasource(dsId, ifaceId);

		return Arc.DEFAULT_ARC;
	}

	private void verifyDatasource(final String dsId, final String ifaceId) throws Exception {
		final StringWriter sw = new StringWriter();

		sw.append("for $x in collection('/db/DRIVER/MetaWorkflowDSResources/MetaWorkflowDSResourceType') where");
		sw.append("  $x//DATAPROVIDER/@id = '" + dsId + "' and ");
		sw.append("  $x//DATAPROVIDER/@interface = '" + ifaceId + "' and ");
		sw.append("  $x//RESOURCE_IDENTIFIER/@value != '" + metaWfId + "' ");
		sw.append("return $x//RESOURCE_IDENTIFIER/@value/string()");

		final boolean active = !serviceLocator.getService(ISLookUpService.class).quickSearchProfile(sw.toString()).isEmpty();

		log.info(" - Updating iface, active status: " + active);

		setActivationStatus(dsId, ifaceId, active);
	}

	protected void setActivationStatus(final String dsId, final String ifaceId, final boolean active) throws Exception {
		dsManager.setActive(dsId, ifaceId, active);
	}

	public String getMetaWfId() {
		return metaWfId;
	}

	public void setMetaWfId(final String metaWfId) {
		this.metaWfId = metaWfId;
	}

}
