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

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.collect.Maps;
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.metawf.DatasourceMetaWorkflow;
import eu.dnetlib.msro.workflows.metawf.DatasourceMetaWorkflowFactory;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants.WorkflowStatus;

public class UpdateMetaWfJobNode extends SimpleJobNode {

	@Resource
	private UniqueServiceLocator serviceLocator;

	@Resource
	private DatasourceMetaWorkflowFactory datasourceMetaWorkflowFactory;

	private String beanName;

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

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

		serviceLocator.getService(ISRegistryService.class).updateProfileNode(metaWfId, "//CONFIGURATION/@status", "'" + WorkflowStatus.WAIT_SYS_SETTINGS + "'");

		final Map<String, String> map = Maps.newHashMap();
		for (String s : token.getFullEnv().getAttributeNames()) {
			map.put(s, token.getFullEnv().getAttribute(s));
		}
		for (String s : token.getEnv().getAttributeNames()) {
			map.put(s, token.getEnv().getAttribute(s));
		}

		final DatasourceMetaWorkflow prototypeMetaWf = datasourceMetaWorkflowFactory.newMetaWorkflow(beanName);

		log.info("Updating metaWorkflow of type: " + beanName);

		final int count = prototypeMetaWf.registerAllWorkflows(map);
		log.info("  -- Registered wfs: " + count);

		final String repoByeId = prototypeMetaWf.registerDestroyWorkflow(map);
		log.info("  -- Repo Bye Wf: " + repoByeId);

		updateDatasourceWorkflow(metaWfId, repoByeId, prototypeMetaWf.asXML());
		log.info("Done");

		return Arc.DEFAULT_ARC;
	}

	protected boolean updateDatasourceWorkflow(final String id, final String repoByeId, final String metawf) throws ISRegistryException, IOException {
		final StringWriter sw = new StringWriter();
		sw.append("<CONFIGURATION status='");
		sw.append(WorkflowStatus.WAIT_USER_SETTINGS.toString());
		sw.append("' destroyWorkflow='");
		sw.append(repoByeId);
		sw.append("'>");
		sw.append(metawf);
		sw.append("</CONFIGURATION>");
		return serviceLocator.getService(ISRegistryService.class).updateProfileNode(id, "//CONFIGURATION", sw.toString());
	}

	@Override
	public String getBeanName() {
		return beanName;
	}

	@Override
	public void setBeanName(final String name) {
		this.beanName = name;
	}
}
