/**
 * SetReencodeVariablesAction.java
 * Created on Jul 15, 2008
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.pmm.action.asset.processing;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import com.tandbergtv.watchpoint.pmm.util.PathConverter;

/**
 * @author Vlada Jakobac
 * 
 */
public class SetReencodeVariablesAction implements ActionHandler {

	private static final Logger logger = Logger
			.getLogger(SetReencodeVariablesAction.class);
	private static final long serialVersionUID = 6510671693435967893L;
	public static String ASSET_PROCESSING_PROPERTIES = "/template-actions/assetProcessing.properties";

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws Exception {
		InputStream stream = this.getClass().getResourceAsStream(
				ASSET_PROCESSING_PROPERTIES);
		Properties config = new Properties();
		config.load(stream);

		/* set the REENCODE output file path */
		String pureFileName = extractFileName(context.getVariable(
				"combinedVideoPath").toString());
		String extension = config.getProperty("reencode.default");
		String profileName = getStringValue(context, "EncodingProfile");
		int dotIndex = profileName.lastIndexOf(".");
		if (dotIndex != -1)
			profileName = profileName.substring(0, dotIndex);
		String reencodeOutputFilePath = context.getVariable("outputDirectory")
				.toString()
				+ File.separator + pureFileName + "_" + profileName + extension;;
		context.setVariable("reencodeOutputFile", reencodeOutputFilePath);
		context.setVariable("reencodeOutputFileUNC", PathConverter
				.getInstance().convertUnixToUNC(reencodeOutputFilePath));
		logger.debug("reencodeOutputFile=" + reencodeOutputFilePath);

	}

	private String extractFileName(String filePath) {
		File f = new File(filePath);
		String fileName = f.getName();
		int dotIndex = fileName.lastIndexOf(".");
		if (dotIndex != -1) {
			return fileName.substring(0, dotIndex);
		} else
			return fileName;

	}

	/*
	 * Return the value of a process variable as a string, irrespective of the
	 * variable type
	 */
	private String getStringValue(ExecutionContext context, String variableName) {
		Object value = context.getVariable(variableName);
		return (value == null) ? null : value.toString();
	}

}
