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

import java.util.List;

import javax.annotation.Resource;

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

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.rmi.MSROException;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants.WorkflowStatus;

public class UpdateMetaWfStatusJobNode extends SimpleJobNode {

	@Resource
	private UniqueServiceLocator serviceLocator;

	@Override
	protected String execute(final NodeToken token) throws Exception {
		final String metaWfId = token.getFullEnv().getAttribute("META_WORKFLOW_ID");

		final String dsId = token.getFullEnv().getAttribute(WorkflowsConstants.DATAPROVIDER_ID);
		final String ifaceId = token.getFullEnv().getAttribute(WorkflowsConstants.DATAPROVIDER_INTERFACE);

		updateDatasource(dsId, ifaceId);

		if (isReady(metaWfId)) {
			serviceLocator.getService(ISRegistryService.class).updateProfileNode(metaWfId, "//CONFIGURATION/@status", "'" + WorkflowStatus.EXECUTABLE + "'");
		}

		return Arc.DEFAULT_ARC;
	}

	protected void updateDatasource(final String dsId, final String ifaceId) throws Exception {
		serviceLocator.getService(ISRegistryService.class).updateProfileNode(dsId, "//INTERFACE[@id = '" + ifaceId + "']/@active", "'true'");
	}

	private boolean isReady(final String metaWfId) throws Exception {
		final String query = "for $x in collection('/db/DRIVER/MetaWorkflowDSResources/MetaWorkflowDSResourceType')"
				+ "//RESOURCE_PROFILE[.//RESOURCE_IDENTIFIER/@value eq '" + metaWfId + "']//WORKFLOW/@id "
				+ "for $y in collection('/db/DRIVER/WorkflowDSResources/WorkflowDSResourceType') " + "where $y//RESOURCE_IDENTIFIER/@value = $x "
				+ "return $y//PARAM[@required='true' and string-length(text()) = 0]/@managedBy/string()";

		final List<String> list = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(query);

		if (list.contains("system")) { throw new MSROException("A system param is missing in profile: " + metaWfId); }

		return list.isEmpty();
	}

}
