package com.tandbergtv.watchpoint.pmm.action.asset.creation;

import java.io.File;

import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import com.tandbergtv.watchpoint.pmm.util.PathConverter;
import com.tandbergtv.watchpoint.pmm.util.PathProperties;

public class SetPackageLocationAction implements ActionHandler{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -1103703335509984122L;

	public void execute(ExecutionContext context) throws Exception {
		
		String exportPathUNC = getStringValue(context, AssetCreationVariables.EXPORT_PATH.toString());
		/* conver export path to linux */
		String exportPath = PathConverter.getInstance().convertUNCToUnix(exportPathUNC);
		
		String packageFileName = getStringValue(context,AssetCreationVariables.PACKAGE_NAME.toString()) +
			"." + getStringValue(context, AssetCreationVariables.PACKAGE_FORMAT.toString());
		File f = new File(exportPath, packageFileName);
		
		/* set package location */
		context.setVariable(AssetCreationVariables.PACKAGE_LOCATION.toString(), f.getAbsolutePath());
		
		/* compute package destination location */
		String providerID = getStringValue(context, AssetCreationVariables.PROVIDER_ID.toString());
		String titleID = getStringValue(context, AssetCreationVariables.TITLE_ID.toString());
		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);
		sb.append(File.separator);
		sb.append(PathProperties.getProperty(PathProperties.PROCESSED_TITLE_PACKAGE));
		
		String destPath = sb.toString();
		File dest = new File(destPath);
		
		if(!dest.exists()){
			dest.mkdirs();
		}
		/* build the path including the package name */
		dest = new File(destPath, packageFileName);
		context.setVariable(AssetCreationVariables.PACKAGE_DESTINATION_LOCATION.toString(),
				dest.getAbsolutePath());
		
		
		
	}
	/* 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();
	}
	
}
