/*
 * Created on Jul 15, 2008 (C) Copyright TANDBERG Television Ltd.
 */

package com.tandbergtv.watchpoint.pmm.action.schedule.distribution;

import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import com.tandbergtv.watchpoint.pmm.action.ActionException;
import com.tandbergtv.watchpoint.pmm.util.TemplateProperties;
import com.tandbergtv.workflow.util.ApplicationProperties;
import com.tandbergtv.workflow.util.ApplicationPropertyKeys;

/**
 * @author Vijay Silva
 */
public class UnapprovedScheduleLoop implements ActionHandler {

	/* Serialization UID */
	private static final long serialVersionUID = 4362877432989507726L;

	/* Template Property for the Schedule URL */
	private static final String SCHEDULE_URL_PROPERTY = "ScheduleDistribution.ScheduleURL";

	/* Template Property for the Schedule Approval Instructions */
	private static final String APPROVAL_INSTRUCTION_PROPERTY = "ScheduleDistribution.ScheduleApprovalInstructions";

	/**
	 * Initialize / Update the Loop variables for the unapproved schedule Ids
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws Exception {
		/* Get the list of unapproved schedule IDs and split */
		String value = this.getStringValue(context, Variables.UNAPPROVED_SCHEDULE_IDS);
		String[] scheduleIds = (value != null) ? value.split(",") : null;

		/* Determine the schedule count and the current index for the schedule to process */
		int scheduleCount = (scheduleIds != null) ? scheduleIds.length : 0;
		int currentIndex = this.getIntValue(context, Variables.UNAPPROVED_SCHEDULE_INDEX, -1) + 1;
		long scheduleId = -1;

		/* Get the next schedule Id */
		while (currentIndex < scheduleCount) {
			String scheduleIdValue = scheduleIds[currentIndex];
			if (scheduleIdValue != null && scheduleIdValue.trim().length() > 0) {
				scheduleId = Long.parseLong(scheduleIdValue.trim());
				break;
			}
			currentIndex++;
		}

		/* Build the schedule URL and determine if there are any more schedules */
		Boolean moreUnapprovedSchedules = (scheduleId != -1);
		String scheduleURL = null;
		String instructions = null;
		if (scheduleId != -1) {
			scheduleURL = this.getApplicationURL();
			if (!(scheduleURL.endsWith("/"))) {
				scheduleURL += "/";
			}
			scheduleURL += TemplateProperties.getString(SCHEDULE_URL_PROPERTY) + scheduleId;
			instructions = TemplateProperties.getString(APPROVAL_INSTRUCTION_PROPERTY);

		}

		context.setVariable(Variables.MORE_UNAPPROVED_SCHEDULES, moreUnapprovedSchedules);
		context.setVariable(Variables.UNAPPROVED_SCHEDULE_INDEX, currentIndex);
		context.setVariable(Variables.SCHEDULE_ID, scheduleId);
		context.setVariable(Variables.SCHEDULE_URL, scheduleURL);
		context.setVariable(Variables.APPROVAL_INSTRUCTIONS, instructions);
	}

	/* Get the Application URL */
	private String getApplicationURL() throws ActionException {
		try {
			ApplicationProperties properties = ApplicationProperties.getInstance();
			return properties.getProperty(ApplicationPropertyKeys.APPLICATION_URL);
		} catch (Exception e) {
			String msg = "Failed to get the Application URL from the "
					+ "Workflow Application Properties, error: " + e.getMessage();
			throw new ActionException(msg, e);
		}
	}

	/* Get the string value for a variable */
	private String getStringValue(ExecutionContext context, String name) {
		Object value = context.getVariable(name);
		return (value != null) ? value.toString() : null;
	}

	/* Get the integer value for a variable */
	private int getIntValue(ExecutionContext context, String name, int defaultValue) {
		int intValue = defaultValue;

		Object value = context.getVariable(name);
		if (value instanceof Number) {
			Number numberValue = (Number) value;
			intValue = numberValue.intValue();
		} else if (value != null) {
			intValue = Integer.parseInt(value.toString());
		}

		return intValue;
	}
}
