/*
 * Created on 2004-1-24
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package workflow.wfmc.xpdl;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.MethodUtils;

import com.zosatapo.commons.util.converters.ClassConverter;
/**
 * @author reic
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public final class WorkflowParameter extends XPDLObject
{
	private Class type;
	private Object value;
  
	public WorkflowParameter()
	{
		super();
	}
  
	public WorkflowParameter(String id, String name, Class type)
	{
		this(id, name, type,null);
	}
  
	public WorkflowParameter(
		String id,
		String name,
		Class type,
		Object initialValue)
	{
		super(id, name);
		this.type = type;
    
		this.value = initialValue;
	}
	
  public void setType(Class type_)
	{
		this.type = type_;
	}
	public Class getType()
	{
		return type;
	}
	public void setValue(Object value_)
	{		
		if (value_ == null)
		{
			return;
		}
		if (value_.getClass().getName().equals(type.getName()))
		{
			this.value = value_;
		}
		else
		{			
			if (value_ instanceof String)
			{
				ConvertUtils.register(new ClassConverter(), Class.class);
				value = ConvertUtils.convert((String) value_, type);
			}
			else if(type.isPrimitive())
			{
				value=value_.toString();
			}
			else
			{
				throw new java.lang.IllegalArgumentException("WorkflowParameter#setValue");
			}
		}
	}
  
	public Object getValue()
	{
		return value;
	}
  
  public WorkflowParameter copy()
  throws CloneNotSupportedException
  {
    WorkflowParameter result=new WorkflowParameter(getUUID(), getName(), getType());
    result.setValue(copyValue());   
    return result;
  }
  
	public String toString()
	{
		return "[id="
			+ getUUID()
			+ "] "
			+ "[name="
			+ getName()
			+ "] "
			+ "[type="
			+ getType()
			+ "] "
			+ "[value="
			+ getValue()
			+ "]"
			+ "[description="
			+ getDescription()
			+ "] ";
	}
  
  private Object copyValue() 
  throws CloneNotSupportedException
  {
    if (value == null)
    {
      return null;
    }
    
		if( value instanceof java.lang.String)
		{
			return value;
		}
		else if(type.isPrimitive())
		{
			return value;
		}	
				
    try
    {
      return MethodUtils.invokeMethod(value, "clone", null);
    }
    catch (Exception ex)
    {   	
      System.err.println(value.getClass());
      throw new CloneNotSupportedException("[class="+value.getClass()+",value="+value.toString()+"]");
    }
  } 
}
