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

import javax.annotation.Resource;

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

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

public class ValidateDatasourceJobNode extends SimpleJobNode {

	@Resource
	private UniqueServiceLocator serviceLocator;

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

	@Override
	protected String execute(final NodeToken token) throws Exception {
		String oldId = token.getFullEnv().getAttribute(WorkflowsConstants.DATAPROVIDER_ID);
		String newId = registerDatasourceWorkflow(oldId);
		token.getFullEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_ID, newId);
		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_ID, newId);

		log.info("Validated datasource - OLD ID: " + oldId);
		log.info("Validated datasource - NEW ID: " + newId);

		return Arc.DEFAULT_ARC;
	}

	public String registerDatasourceWorkflow(final String oldId) throws ISRegistryException {
		return serviceLocator.getService(ISRegistryService.class).validateProfile(oldId);
	}
}
