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

import java.util.Date;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;

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

import eu.dnetlib.enabling.datasources.common.LocalDatasourceManager;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.miscutils.datetime.DateUtils;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;

public class ObjectStoreToApiExtraFieldJobNode extends SimpleJobNode {

	private String objId;
	private String datasourceId;
	private String datasourceInterface;
	@Deprecated
	private String extraFieldForTotal;
	@Deprecated
	private String extraFieldForDate;
	@Deprecated
	private String extraFieldForObjId;

	@Autowired
	private UniqueServiceLocator serviceLocator;

	@Autowired
	private LocalDatasourceManager<?, ?> dsManager;

	@Override
	protected String execute(final NodeToken token) throws Exception {
		final String xq = "for $x in collection('/db/DRIVER/ObjectStoreDSResources/ObjectStoreDSResourceType') " + "where $x//RESOURCE_IDENTIFIER/@value='"
				+ objId + "' " + "return concat($x//COUNT_STORE, ' @=@ ', $x//LAST_STORAGE_DATE)";

		final String s = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(xq);

		final String[] arr = s.split(" @=@ ");

		final int size = NumberUtils.toInt(arr[0].trim(), 0);
		final Date date = (new DateUtils()).parse(arr[1]);

		dsManager.setLastDownloadInfo(datasourceId, datasourceInterface, objId, size, date);

		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 getExtraFieldForTotal() {
		return extraFieldForTotal;
	}

	public void setExtraFieldForTotal(final String extraFieldForTotal) {
		this.extraFieldForTotal = extraFieldForTotal;
	}

	public String getExtraFieldForDate() {
		return extraFieldForDate;
	}

	public void setExtraFieldForDate(final String extraFieldForDate) {
		this.extraFieldForDate = extraFieldForDate;
	}

	/**
	 * @return the objId
	 */
	public String getObjId() {
		return objId;
	}

	/**
	 * @param objId
	 *            the objId to set
	 */
	public void setObjId(final String objId) {
		this.objId = objId;
	}

	/**
	 * @return the extraFieldForObjId
	 */
	public String getExtraFieldForObjId() {
		return extraFieldForObjId;
	}

	/**
	 * @param extraFieldForObjId
	 *            the extraFieldForObjId to set
	 */
	public void setExtraFieldForObjId(final String extraFieldForObjId) {
		this.extraFieldForObjId = extraFieldForObjId;
	}

}
