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

import javax.annotation.Resource;

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

import eu.dnetlib.data.objectstore.rmi.ObjectStoreService;
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.miscutils.datetime.DateUtils;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;

// TODO: Auto-generated Javadoc
/**
 * The Class UpdateObjectStoreSizeJobNode.
 */
public class UpdateObjectStoreSizeJobNode extends SimpleJobNode {

	/** The object store id. */
	private String objectStoreIdParam;

	/** The service locator. */
	@Resource
	private UniqueServiceLocator serviceLocator;

	/*
	 * (non-Javadoc)
	 * 
	 * @see eu.dnetlib.msro.workflows.nodes.SimpleJobNode#execute(com.googlecode.sarasvati.NodeToken)
	 */
	@Override
	protected String execute(final NodeToken token) throws Exception {

		final ISRegistryService registry = serviceLocator.getService(ISRegistryService.class);

		int size = serviceLocator.getService(ObjectStoreService.class, objectStoreIdParam).getSize(objectStoreIdParam);

		String now = DateUtils.now_ISO8601();

		String mdstoreXUpdate = "for $x in //RESOURCE_PROFILE[.//RESOURCE_IDENTIFIER/@value = '" + objectStoreIdParam + "']"
				+ "return update value $x//LAST_STORAGE_DATE with '" + now + "'";

		registry.executeXUpdate(mdstoreXUpdate);

		String mdstoreNumberXUpdate = "for $x in //RESOURCE_PROFILE[.//RESOURCE_IDENTIFIER/@value = '" + objectStoreIdParam + "']"
				+ "return update value $x//COUNT_STORE with '" + size + "'";

		registry.executeXUpdate(mdstoreNumberXUpdate);

		mdstoreNumberXUpdate = "for $x in //RESOURCE_PROFILE[.//RESOURCE_IDENTIFIER/@value = '" + objectStoreIdParam + "']"
				+ "return update value $x//STORE_SIZE with '" + size + "'";

		registry.executeXUpdate(mdstoreNumberXUpdate);

		return Arc.DEFAULT_ARC;
	}

	/**
	 * Gets the object store id param.
	 *
	 * @return the objectStoreIdParam
	 */
	public String getObjectStoreIdParam() {
		return objectStoreIdParam;
	}

	/**
	 * Sets the object store id param.
	 *
	 * @param objectStoreIdParam
	 *            the new object store id param
	 */
	public void setObjectStoreIdParam(final String objectStoreIdParam) {
		this.objectStoreIdParam = objectStoreIdParam;
	}

}
