/**
 * SetVariables.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.FilePermissionUtility;
import com.tandbergtv.watchpoint.pmm.util.PathConverter;
import com.tandbergtv.watchpoint.pmm.util.PathProperties;

/**
 * @author Vlada Jakobac
 * 
 */
public class SetVariables implements ActionHandler {

	private static final long serialVersionUID = 6510671693435967893L;
	private static final Logger logger = Logger.getLogger(SetVariables.class);
	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);

		String providerID = getStringValue(context, "providerId");
		String titleID = getStringValue(context, "titleId");

		StringBuffer sb = getTitlesPath(providerID, titleID);
		sb.append(File.separator);
		sb.append(PathProperties.getProperty(PathProperties.PROCESSED_TITLE_ASSET));

		String destPath = sb.toString();
		File dest = new File(destPath);
		logger.debug("destPath=" + destPath);
		if (!dest.exists()) {
			dest.mkdirs();
		}
		FilePermissionUtility.setPermissions(dest);

		context.setVariable("outputDirectory", destPath);

		/* set the combinedVideoPath */
		boolean combineWithAd = (Boolean) context.getVariable("combineWithAd");
		if (!combineWithAd) {
			context.setVariable("combinedVideoPath", context
					.getVariable("movieFilePath"));
			context.setVariable("combinedVideoPathUNC", PathConverter
					.getInstance().convertUnixToUNC(context.getVariable("movieFilePath").toString()));
		} else {
			String movieFilePath = getStringValue(context, "movieFilePath");
			String movieFilePathUNC = PathConverter.getInstance().convertUnixToUNC(movieFilePath);
			context.setVariable("movieFilePathUNC", movieFilePathUNC);			
			String movieFileName = (new File(movieFilePath)).getName();
			String combinedVideoPath = destPath + File.separator
					+ movieFileName;
			context.setVariable("combinedVideoPath", combinedVideoPath);
			context.setVariable("combinedVideoPathUNC", PathConverter
					.getInstance().convertUnixToUNC(combinedVideoPath));
			logger.debug("combinedVideoPath=" + combinedVideoPath);
			
			/* set the ads file paths: UNC paths needed for Mediaware */
			String preRollAdFilePath = getStringValue(context, "preRollAdFilePath");
			String preRollAdFilePathUNC = PathConverter.getInstance().convertUnixToUNC(preRollAdFilePath);
			context.setVariable("preRollAdFilePathUNC", preRollAdFilePathUNC);
			String postRollAdFilePath = getStringValue(context, "postRollAdFilePath");
			String postRollAdFilePathUNC = PathConverter.getInstance().convertUnixToUNC(postRollAdFilePath);
			context.setVariable("postRollAdFilePathUNC", postRollAdFilePathUNC);
			String inputFilesPathsListUNC="";
			if (preRollAdFilePath != null && !preRollAdFilePath.equals(""))
				inputFilesPathsListUNC = preRollAdFilePathUNC + "," + movieFilePathUNC;
			else 
				inputFilesPathsListUNC = movieFilePathUNC;
			if (postRollAdFilePath != null && !postRollAdFilePath.equals(""))
				inputFilesPathsListUNC += "," + postRollAdFilePathUNC;
			context.setVariable("inputFilesPathsListUNC", inputFilesPathsListUNC);
			
		}

		/* set the tarDestination */
		StringBuffer tarSB = getTitlesPath(providerID, titleID);
		tarSB.append(File.separator);
		tarSB.append(PathProperties.getProperty(PathProperties.PROCESSED_TITLE_PACKAGE));
		String archiveExtension = ".";
		String archiveType = getStringValue(context, "archiveType");	
		if (archiveType != null && !archiveType.trim().equals("")){
			archiveExtension += archiveType;
		} else {
			archiveExtension += "tar";
		}
		logger.debug("archiveExtension="+archiveExtension+".");
		String tarDestinationFolder = tarSB.toString();
		String tarDestinationFile = tarDestinationFolder + File.separator
				+ getStringValue(context, "packageName") + archiveExtension;
		File tarDest = new File(tarDestinationFolder);
		logger.debug("tarDestinationFolder=" + tarDestinationFolder);
		if (!tarDest.exists()) {
			tarDest.mkdirs();
		}
		FilePermissionUtility.setPermissions(tarDest);
		logger.debug("tarDestinationFile=" + tarDestinationFile);
		context.setVariable("tarDestination", tarDestinationFile);
		
		context.setVariable("tarFilepath", "tarFilepath");
	}

	private StringBuffer getTitlesPath(String providerID, String titleID) {
		StringBuffer sb = new StringBuffer();

		sb.append(PathProperties.getProperty(PathProperties.CONTENT_PATH));
		sb.append(File.separator);
		sb.append(providerID);
		sb.append(File.separator);
		sb.append(PathProperties.getProperty(PathProperties.PROCESSED_TITLES_PATH));
		sb.append(File.separator);
		sb.append(titleID);
		return sb;
	}

	/*
	 * 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();
	}
}
