/**
 * SetFileArchivalPathAction.java
 * Created on Jun 30, 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.PathProperties;
import com.tandbergtv.watchpoint.pmm.util.schedule.ingest.FileType;

/**
 * This class sets the 'archiveFilepath' variable in the context.
 * 
 * @author spuranik
 */
public class SetFileArchivalPathAction implements ActionHandler {

	private static final long serialVersionUID = 1L;

	private static final String ARCHIVE_FILE_PATH = "archiveFilepath";
	private static String FILEPATH = "filePath";
	private static String FILE_TYPE = "type";
	private static String SOURCE_PROVIDER_ID = "providerId";
	private static String PROCESS_ID = "processId";
	
	private static String FILE_NAME_DELIMITER = "_";

	private static final Logger logger = Logger.getLogger(SetFileArchivalPathAction.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws Exception {

		String root = PathProperties.getProperty(PathProperties.CONTENT_PATH);
		String providerId = (String) context.getVariable(SOURCE_PROVIDER_ID);

		String archiveFolder = "";
		String fileType = (String) context.getVariable(FILE_TYPE);

		// currently, since file type is set only after conversion, the original
		// file is always written to the PLANNER folder.
		if (fileType.equals(FileType.PROGRAM_LIST.getValue())) {
			String programListPath = PathProperties
					.getProperty(PathProperties.ORIGINAL_PROGRAM_LIST_PATH);
			archiveFolder = root + File.separator + providerId + File.separator + programListPath;
		} else {
			String plannerPath = PathProperties.getProperty(PathProperties.ORIGINAL_PLANNER_PATH);
			archiveFolder = root + File.separator + providerId + File.separator + plannerPath;
		}

		// create the archive directory if its not already there.
		File dirFile = new File(archiveFolder);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		// set the complete filepath for the archive file
		String inputFilepath = (String) context.getVariable(FILEPATH);
		File inputFile = new File(inputFilepath);
		String archiveFilePath = archiveFolder + File.separator
				+ context.getVariable(PROCESS_ID) + FILE_NAME_DELIMITER
				+ inputFile.getName();

		context.setVariable(ARCHIVE_FILE_PATH, archiveFilePath);

		logger.debug("Set archivePath to: " + archiveFilePath);
	}

}
