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

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.math.NumberUtils;
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.common.logging.DnetLogger;
import eu.dnetlib.msro.rmi.MSROException;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;

public class FindDateRangeForIncrementalHarvestingJobNode extends SimpleJobNode {
	
	private String fromDateParam;
	private String untilDateParam;
	private long ONE_DAY = 1000 * 60 * 60 * 24;	
	
	@Resource(name = "msroWorkflowLogger")
	private DnetLogger dnetLogger;
	
	private static final Log log = LogFactory.getLog(FindDateRangeForIncrementalHarvestingJobNode.class);
	
	@Override
	protected String execute(NodeToken token) throws Exception {
		final String profId = findCurrentWfProfileId(token);
		final String fromDate = calculateFromDate(profId); 
		final String untilDate = null;
		
		log.info("Incremental Harv Details - profId: " + profId + " - from: " + fromDate + " - until: " + untilDate);
		
		if (fromDate != null) {
			token.getEnv().setAttribute(getFromDateParam(), fromDate);
		}
		
		//if (untilDate != null) {
		//	token.getEnv().setAttribute(getUntilDateParam(), untilDate);
		//}
		
		return Arc.DEFAULT_ARC;
	}	
	
	private String calculateFromDate(final String profId) {
		final long d = findLastSuccessStartDate(profId);
		return (d > 0) ? (new SimpleDateFormat("yyyy-MM-dd")).format(new Date(d - ONE_DAY)) : null;
	}

	private long findLastSuccessStartDate(String profId) {
		long res = -1;
		
		final Iterator<Map<String, String>> iter = dnetLogger.find(WorkflowsConstants.SYSTEM_WF_PROFILE_ID, profId);
		while (iter.hasNext()) {
			final Map<String, String> map = iter.next();
			if ("true".equalsIgnoreCase(map.get(WorkflowsConstants.SYSTEM_COMPLETED_SUCCESSFULLY))) {
				final long curr = NumberUtils.toLong(map.get(WorkflowsConstants.SYSTEM_START_DATE), -1);
				if (curr > res) {
					res = curr;
				}
			}
		}
		return res;
	}

	private String findCurrentWfProfileId(NodeToken token) throws MSROException {
		final String p1 = token.getEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
		if (p1 != null && !p1.isEmpty()) {
			return p1;
		}
		final String p2 = token.getFullEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
		if (p2 != null && !p2.isEmpty()) {
			return p2;
		}
		final String p3 = token.getProcess().getEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
		if (p3 != null && !p3.isEmpty()) {
			return p3;
		}
		throw new MSROException("Missing property in env: " + WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
	}

	public String getFromDateParam() {
		return fromDateParam;
	}
	public void setFromDateParam(String fromDateParam) {
		this.fromDateParam = fromDateParam;
	}
	public String getUntilDateParam() {
		return untilDateParam;
	}
	public void setUntilDateParam(String untilDateParam) {
		this.untilDateParam = untilDateParam;
	}
	
}
