/*
 * Created on Jul 14, 2008 (C) Copyright TANDBERG Television Ltd.
 */

package com.tandbergtv.watchpoint.pmm.action.schedule.distribution;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

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.PathProperties;
import com.tandbergtv.watchpoint.pmm.util.TemplateProperties;

/**
 * Initialize variables / constants for the schedule distribution template
 * 
 * @author Vijay Silva
 */
public class Initialize implements ActionHandler {

	/* Serialization UID */
	private static final long serialVersionUID = 362440281934030747L;

	/**
	 * Initializes the constants used by the template.
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws ActionException {
		/* Get the current Start Date value or update if not present */
		Date startDate = null;
		Object value = context.getVariable(Variables.START_DATE);
		if (value instanceof Date) {
			startDate = (Date) value;
		} 

		/* Validate that the start date exists */
		if (startDate == null) {
			String msg = "Failed to get the Start Date required when searching"
					+ " for Pitch Schedules for distribution.";
			throw new ActionException(msg);
		}

		/* Set the formatted start date */
		DateFormat format = new SimpleDateFormat(TemplateProperties.getString("PMM.date.format"));
		String formattedStartDate = format.format(startDate);
		context.setVariable(Variables.FORMATTED_START_DATE, formattedStartDate);

		/* Create the Pitch Schedule Folder for the partner / service */
		String contextName = context.getVariable(Variables.CONTEXT_NAME).toString();
		String folderPath = PathProperties.getProviderPath(contextName,
				PathProperties.PROCESSED_PITCH_SCHEDULE_PATH);
		File schedulesFolder = new File(folderPath);

		if (!schedulesFolder.exists() && !schedulesFolder.mkdirs()) {
			throw new ActionException("Failed to create folder structure for path: " + folderPath
					+ " required for Pitch Schedule Distribution.");
		}

		if (!schedulesFolder.isDirectory()) {
			throw new ActionException("The path: " + folderPath + " is not a directory path, "
					+ "cannot generate Pitch Schedule file for distribution.");
		}

		/* Generate the internal and distribution format file paths */
		String baseFileName = "PitchSchedules_" + context.getToken().getId();
		String fileName = baseFileName + "_internal.xml";
		String internalFilePath = new File(folderPath, fileName).getAbsolutePath();
		String distributionFilePath = new File(folderPath, baseFileName).getAbsolutePath();
		context.setVariable(Variables.SCHEDULE_FILE_PATH_INTERNAL, internalFilePath);
		context.setVariable(Variables.SCHEDULE_FILE_PATH_DISTRIBUTION, distributionFilePath);
		
		/* Calculate and Set the value of the date range variable */
		int numOfDays = ((Integer) context.getVariable(Variables.NUMBER_OF_DAYS)).intValue();
		Calendar endDateCal = Calendar.getInstance();
		endDateCal.setTime(startDate);
		endDateCal.add(Calendar.DATE, numOfDays);
		String dateRange = formattedStartDate + " to " + format.format(endDateCal.getTime());
		context.setVariable(Variables.DATE_RANGE, dateRange);
	}
}
