package com.tandbergtv.watchpoint.pmm.action.asset.arrival;

import java.io.File;

import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import com.tandbergtv.watchpoint.pmm.action.ActionException;
import com.tandbergtv.watchpoint.pmm.util.FilePermissionUtility;
import com.tandbergtv.watchpoint.pmm.util.PathProperties;

/**
 * Creates the original files directory.
 * 
 * @author Raj Prakash
 */
public class MakeOriginalFilesDirectory implements ActionHandler {

	private static final long serialVersionUID = -5933623971869147450L;

	/* (non-Javadoc)
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws Exception {
		//get file path from context
		String filePath = getStringValue(context, Variables.INPUT_FILE_PATH);
		File file = new File(filePath);
		
		//prepare original file directory path for this file
		String providerId = getStringValue(context, Variables.PROVIDER_ID);
		
		String originalAssetDirPath = PathProperties.getProviderPath(providerId,
				PathProperties.ORIGINAL_ASSET_PATH);
		File originalAssetDir = new File(originalAssetDirPath);
		
		String originalFileDirName = file.getName() + "_" + System.currentTimeMillis();
		File originalFileDir = new File(originalAssetDir, originalFileDirName);
		
		//make original file directory
		if(!originalFileDir.mkdirs()) {
			throw new ActionException("Unable to create directory: " + originalFileDir);
		}
		FilePermissionUtility.setPermissions(originalFileDir);
		
		//set the original file dir path to context
		context.setVariable(Variables.STAGING_PATH, originalFileDir.getAbsolutePath());
	}
	
	/*
	 * Gets the String value of the variable (in case the data type is not string). Uses toString()
	 * for all data types.
	 */
	private String getStringValue(ExecutionContext context, String variableName) {
		Object value = context.getVariable(variableName);
		return (value != null) ? value.toString() : null;
	}
}
