/*
 * Created on Jun 25, 2008 (C) Copyright TANDBERG Television Ltd.
 */

package com.tandbergtv.watchpoint.pmm.action;

import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import com.tandbergtv.watchpoint.pmm.util.TemplateProperties;

/**
 * @author Vijay Silva
 */
public class AssignResource implements ActionHandler {

	/* Serialization Id */
	private static final long serialVersionUID = -8283045339910414982L;

	/* The Property for the variable name to use when assigning a specific resource */
	private static final String ASSIGNED_RESOURCE_VARIABLE = "General.AssignResourceVariable";

	/* The Constant value to use for assigning a resource */
	private String assignedResource = null;

	/* The variable name containing the value to use for assigning a resource */
	private String assignedResourceVariable = null;

	/**
	 * Set the Resource Host variable
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws ActionException {
		String resourceHost = null;
		boolean fromVariable = true;

		/* Check the variable first, and then check the constant value */
		if (assignedResourceVariable != null && assignedResourceVariable.trim().length() > 0) {
			Object value = context.getVariable(this.assignedResourceVariable);
			if (value != null)
				resourceHost = value.toString();
		} else {
			resourceHost = this.assignedResource;
			fromVariable = false;
		}

		if (resourceHost == null || resourceHost.trim().length() == 0) {
			String msg = "Failed to set the resource to assign, no value specified for ";
			msg += (fromVariable) ? "variable: " + this.assignedResourceVariable
					: "action property: assignedResource";
			throw new ActionException(msg);
		}

		String variableName = TemplateProperties.getString(ASSIGNED_RESOURCE_VARIABLE);
		variableName += context.getToken().getId();
		context.setVariable(variableName, resourceHost);
	}
}
