/*
 * Created on Jun 30, 2008 (C) Copyright TANDBERG Television Ltd.
 */

package com.tandbergtv.watchpoint.pmm.action.asset.arrival;

import java.io.IOException;

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.TemplateProperties;
import com.tandbergtv.workflow.util.ApplicationProperties;

/**
 * @author Vijay Silva
 */
public class InitializeProcessVariables implements ActionHandler {

	/* Serialization UID */
	private static final long serialVersionUID = -5476552838428097291L;

	/**
	 * Initialize the Constants used by the Template
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws Exception {
		long tokenId = context.getToken().getId();
		long processId = context.getProcessInstance().getId();

		/* Set the Process and Token Id */
		context.setVariable(Variables.TOKEN_ID, Long.toString(tokenId));
		context.setVariable(Variables.PROCESS_ID, Long.toString(processId));

		/* Set the Title Specification value */
		context.setVariable(Variables.TITLE_SPECIFICATION_TYPE, "CL1_1");
		
		context.setVariable(Variables.MAPPING_LOOP_INCOMPLETE, false);
		context.setVariable(Variables.CREATE_TITLE_IF_NOT_EXIST, false);

		// Set if the input file is an archive file
		String inputFilePath = (String) context.getVariable(Variables.INPUT_FILE_PATH);
		boolean isArchiveFile = inputFilePath.toLowerCase().endsWith(".tar");
		context.setVariable(Variables.IS_ARCHIVE_FILE, isArchiveFile);
		
		//Set the titleSearchURL variable
		/* Get the workflow application URL */
		String applicationURL = this.getApplicationProperties().getProperty("application.url");
		if (!applicationURL.endsWith("/"))
			applicationURL += "/";

		/* build the URLs and store the variables */
		String titleSearchURL = applicationURL + TemplateProperties.getString("AssetArrival.TitleSearchURL");
		context.setVariable(Variables.TITLE_SEARCH_URL, titleSearchURL);
		
		/* build and store source-related information */
		context.setVariable(Variables.SOURCE_COMPONENT_NAME, "WatchPoint");
		context.setVariable(Variables.SOURCE_ENTITY_NAME, "Workflow");
		context.setVariable(Variables.SOURCE_ID, Long.toString(processId) + "|" + Long.toString(tokenId));
	}
	
	/* Get the Application Properties for the Workflow Application */
	private ApplicationProperties getApplicationProperties() throws ActionException {
		try {
			return ApplicationProperties.getInstance();
		} catch (IOException e) {
			String msg = "Failed to the get Workflow Application Properties, error: "
					+ e.getMessage();
			throw new ActionException(msg, e);
		}
	}
}
