/**
 * SetPMMSchedulePath.java
 * Created on Aug 1, 2008
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.pmm.action.schedule.ingest;

import java.io.File;

import org.apache.log4j.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import com.tandbergtv.watchpoint.pmm.util.schedule.ingest.ConversionHelper;
import com.tandbergtv.watchpoint.pmm.util.schedule.ingest.FileType;

/**
 * This class sets the file path for the PMM format schedule/program list that was created as a
 * result of the conversion from external to internal format.
 * 
 * @author spuranik
 * 
 */
public class SetPMMSchedulePath implements ActionHandler {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(SetPMMSchedulePath.class);

	// these values should match the ones in the template.
	private static String PROVIDER_ID = "providerId";
	private static String INCOMING_FILE_TYPE = "type";
	private static String FILEPATH = "filePath";
	private static String CONVERTED_FILEPATH = "convertedFilepath";
	private static String PROCESS_ID = "processId";
	
	private static String FILE_NAME_DELIMITER = "_";

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws Exception {
		String providerId = (String) context.getVariable(PROVIDER_ID);
		String type = (String) context.getVariable(INCOMING_FILE_TYPE);
		String inputFilepath = (String) context.getVariable(FILEPATH);

		String outputFolder = ConversionHelper
				.getOutputPath(providerId, FileType.getFileType(type));
		// if the output folder does not exist, create it.
		File dirFile = new File(outputFolder);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		
		String outputFilename = context.getVariable(PROCESS_ID)
				+ FILE_NAME_DELIMITER
				+ ConversionHelper.getFilename(inputFilepath);		
		String outputPath = ConversionHelper.generateFileName(outputFolder, outputFilename);

		context.setVariable(CONVERTED_FILEPATH, outputPath);
		logger.debug("Set converted file path to: " + outputPath);
	}
}
