package eu.dnetlib.msro.workflows.util;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.sarasvati.GraphProcess;
import com.googlecode.sarasvati.NodeToken;

public class ProcessUtils {
	
	private static String oldGeneratedId = "";	
	
	private static final Log log = LogFactory.getLog(ProcessUtils.class); 
	
	public static String calculateName(final GraphProcess process) {
		return process.getGraph().getName();
	}

	public static String calculateFamily(final GraphProcess process) {
		return process.getEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_FAMILY);
	}
	
	public static String calculateWfId(final GraphProcess process) {
		return  process.getEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
	}
	
	public static String calculateStatus(final GraphProcess process) {
		if (!process.isComplete()) {
			return process.getState().toString().toUpperCase();
		} else if ("true".equals(process.getEnv().getAttribute(WorkflowsConstants.SYSTEM_COMPLETED_SUCCESSFULLY))) {
			return "SUCCESS";
		} else {
			return "FAILURE";
		}
	}
	
	public static Date calculateLastActivityDate(final GraphProcess process) {
		Date date = null;
		for (final NodeToken token : process.getNodeTokens()) {
			Date activity = token.getCompleteDate();
			if (activity == null)
				activity = token.getCreateDate();

			if (date == null)
				date = activity;

			if (activity != null && date != null && activity.compareTo(date) > 0)
				date = activity;
		}
		return date;
	}

	public static String calculateRepo(final GraphProcess process) {
		if (process.getEnv().hasAttribute(WorkflowsConstants.DATAPROVIDER_NAME)) {
			return process.getEnv().getAttribute(WorkflowsConstants.DATAPROVIDER_NAME);
		}
		return "";
	}

	
	public static synchronized String generateProcessId() {
		String id = "";
		do {
			id = "wf_" + (new SimpleDateFormat("yyyyMMdd_HHmmss_S")).format(new Date());
			log.info("Generated processID " + id);
		} while (id.equals(oldGeneratedId));
		
		oldGeneratedId = id;
		
		return id;
	}

}
