package com.citytechinc.repo.workflow.jbpm;


import java.util.Calendar;
import java.util.Date;
import org.alfresco.repo.workflow.jbpm.JBPMSpringActionHandler;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.workflow.WorkflowException;
import org.jbpm.calendar.BusinessCalendar;
import org.jbpm.calendar.Duration;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.taskmgmt.exe.TaskInstance;
import org.springframework.beans.factory.BeanFactory;


/**
 * A jBPM Action Handler for assigning the due date for the current
 * task to "task creation date" + the duration given.
 * 
 * Due date will always fall on a business day per the jBPM business calendar
 * included in Alfresco.
 * 
 * The configuration of this action is as follows:
 * 
 * <addDuration>2 business days</addDuration>
 * 
 * Any valid jBPM duration string may be used such as "2 minutes", "4 business hours", etc.
 * 
 * @author Jeff D. Brown - CityTech, Inc.
 */
public class AssignBusinessDueDate extends JBPMSpringActionHandler {
	private static final long serialVersionUID = -2908748080671212745L;
	protected static BusinessCalendar businessCalendar = new BusinessCalendar();

	private ServiceRegistry services;
	private String addDuration;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.alfresco.repo.workflow.jbpm.JBPMSpringActionHandler#initialiseHandler(org.springframework.beans.factory.BeanFactory)
	 */
	@Override
	protected void initialiseHandler(BeanFactory factory) {
		services = (ServiceRegistry) factory.getBean(ServiceRegistry.SERVICE_REGISTRY);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	@SuppressWarnings("unchecked")
	public void execute(ExecutionContext executionContext) throws Exception {
		
		if (this.addDuration == null) {
			throw new WorkflowException("addDuration parameter has not been provided");
		}

		Calendar cal = Calendar.getInstance();
		BusinessCalendar businessCalendar = new BusinessCalendar();
		Duration duration = new Duration(this.addDuration);
		Date dueDate = businessCalendar.add(cal.getTime(), duration);
		TaskInstance taskInstance = executionContext.getTaskInstance();
		taskInstance.setDueDate(dueDate);
	}


}
