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

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

import eu.dnetlib.msro.rmi.MSROException;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

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

import eu.dnetlib.data.collector.rmi.CollectorService;
import eu.dnetlib.data.collector.rmi.InterfaceDescriptor;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;

public class CollectRecordsJobNode extends SimpleJobNode {

	@Resource
	private UniqueServiceLocator serviceLocator;

	private String datasourceId;
	private String datasourceInterface;
	private String eprParam;

	@Override
	protected String execute(final NodeToken token) throws Exception {
		final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(datasourceId);
		final Document doc = new SAXReader().read(new StringReader(profile));
		final Node ifcNode = doc.selectSingleNode("//INTERFACE[@id='" + datasourceInterface + "']");

		final InterfaceDescriptor interfaceDescriptor = InterfaceDescriptor.newInstance(ifcNode);

		if (interfaceDescriptor == null) {
			throw new MSROException("invalid interface descriptor: " + datasourceInterface);
		}

		final W3CEndpointReference epr = serviceLocator.getService(CollectorService.class).collect(interfaceDescriptor);

		token.getEnv().setAttribute(getEprParam(), epr.toString());

		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_INTERFACE_BASEURL, interfaceDescriptor.getBaseUrl());
		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_PREFIX + "protocol", interfaceDescriptor.getProtocol());
		final Map<String, String> params = interfaceDescriptor.getParams();
		if (params != null) {
			for(Map.Entry<String, String> e : params.entrySet()) {
				token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_PREFIX + e.getKey(), e.getValue());
			}
		}

		return Arc.DEFAULT_ARC;
	}

	public String getDatasourceId() {
		return datasourceId;
	}

	public void setDatasourceId(final String datasourceId) {
		this.datasourceId = datasourceId;
	}

	public String getDatasourceInterface() {
		return datasourceInterface;
	}

	public void setDatasourceInterface(final String datasourceInterface) {
		this.datasourceInterface = datasourceInterface;
	}

	public String getEprParam() {
		return eprParam;
	}

	public void setEprParam(final String eprParam) {
		this.eprParam = eprParam;
	}

}
