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 unmapped file directory.
 * 
 * @author Raj Prakash
 */
public class MakeUnmappedFilesDirectory 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.MAPPING_LOOP_PATH);
		File file = new File(filePath);
		
		//prepare unmapped file directory path for this file
		String providerId = getStringValue(context, Variables.PROVIDER_ID);

		File providerDir = PathProperties.getUnmappedProviderFolder(providerId);

		String unmappedFileDirName = file.getName() + "_" + System.currentTimeMillis();
		File unmappedFileDir = new File(providerDir, unmappedFileDirName);
		
		//make unmapped file directory
		if(!unmappedFileDir.mkdirs()) {
			throw new ActionException("Unable to create directory: " + unmappedFileDir);
		}
		FilePermissionUtility.setPermissions(unmappedFileDir);
		
		//set the unmapped file path to context
		File unmappedFile = new File(unmappedFileDir, file.getName());
		context.setVariable(Variables.MAPPING_LOOP_UNMAPPED_PATH,
				unmappedFile.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;
	}
}
