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

import java.util.List;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.googlecode.sarasvati.Arc;
import com.googlecode.sarasvati.NodeToken;

import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.enabling.resultset.IterableResultSetFactory;
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;

public class FetchMultipleMDStores extends SimpleJobNode {

	private static final Log log = LogFactory.getLog(FetchMultipleMDStores.class); // NOPMD by marko on 11/24/08 5:02 PM

	@Resource
	private UniqueServiceLocator serviceLocator;

	private List<String> mdId;

	private String eprParam;

	/** The result set factory. */
	@Resource(name = "iterableResultSetFactory")
	private IterableResultSetFactory resultSetFactory;

	/** The result set client factory. */
	@Autowired
	private ResultSetClientFactory resultSetClientFactory;

	@Override
	protected String execute(final NodeToken token) throws Exception {

		if (getMdId() == null) {
			final String mdIdsJson = token.getEnv().getAttribute("mdId");
			@SuppressWarnings("unchecked")
			final List<String> mdIds = new Gson().fromJson(mdIdsJson, List.class);
			log.info(String.format("fetching records for %s mdstores", mdIds.size()));
			if (log.isDebugEnabled()) {
				log.debug(String.format("fetching records for mdstores: %s", mdIdsJson));
			}
			setMdId(mdIds);
		}

		final MultipleMdStoreIterable iter = new MultipleMdStoreIterable(serviceLocator, getMdId(), resultSetClientFactory);
		final W3CEndpointReference epr = resultSetFactory.createIterableResultSet(iter);
		token.getEnv().setAttribute(getEprParam(), epr.toString());
		return Arc.DEFAULT_ARC;
	}

	public List<String> getMdId() {
		return mdId;
	}

	public void setMdId(final List<String> mdId) {
		this.mdId = mdId;
	}

	public String getEprParam() {
		return eprParam;
	}

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

}
