/*
 * FSNewFunction2.java
 * Transform
 * 
 * Copyright (c) 2001-2008 Flagstone Software Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 *  * Neither the name of Flagstone Software Ltd. nor the names of its contributors 
 *    may be used to endorse or promote products derived from this software 
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.flagstone.transform;

import java.util.*;

/**
 * The FSNewFunction2 action is used to create a user-defined function.
 * 
 * <p>
 * It was added in Flash 7 to improve the performance of function calls by
 * allowing variables to be pre-loaded to a set of up to 256 internal registers
 * and controlling the loading of pre-defined variables such as <em>_root</em>,
 * <em>_parent</em>, <em>_global</em>, <em>super</em>, <em>this</em>
 * and the <em>arguments</em> array containing the arguments passed to the
 * function.
 * </p>
 * 
 * <table class="datasheet">
 * 
 * <tr>
 * <th align="left" colspan="2">Attributes</th>
 * </tr>
 * 
 * <tr>
 * <td>name</td>
 * <td>A string defining the name of the function.</td>
 * </tr>
 * 
 * <tr>
 * <td>registerCount</td>
 * <td>The number of registers, up to 256, to allocate for storing variables.</td>
 * </tr>
 * 
 * <tr>
 * <td>optimizations</td>
 * <td>A code consisting of a number of flags that control the execution
 * environment for the function.</td>
 * </tr>
 * 
 * <tr>
 * <td>arguments</td>
 * <td>An array of FSRegisterVariable objects containing the names of the
 * arguments and whether they will be assigned to internal registers or defined
 * in memory as local variables. The order of the FSRegisterVariable objects in
 * the argument array indicate the order in which the values will be popped off
 * the stack when the function is executed. The fist argument is popped from the
 * stack first.</td>
 * </tr>
 * 
 * <tr>
 * <td>actions</td>
 * <td>An array containing the actions that are executed.</td>
 * </tr>
 * 
 * </table>
 * 
 * <p>
 * The optimisation attribute is a compound code, containing a number of flags
 * that control how the environment of the function is initialised. Controlling
 * the pre-defined variables that are created and pre-loading them into
 * registers can significantly improve performance.
 * </p>
 * 
 * <table class="datasheet">
 * <tr>
 * <th align="left">Environment</th>
 * <th align="left">Description</th>
 * </tr>
 * 
 * <tr>
 * <td>CreateSuper</td>
 * <td>Create and initialise the <em>super</em> variable with the parent
 * class of the function.</td>
 * </tr>
 * <tr>
 * <td>CreateArguments</td>
 * <td>Create the <em>arguments</em> variable which contains the arguments
 * passed to the function.</td>
 * </tr>
 * <tr>
 * <td>CreateThis</td>
 * <td>Create the and initialise the <em>this</em> variable with the object.</td>
 * </tr>
 * <tr>
 * <td>LoadThis</td>
 * <td>Pre-load the <em>this</em> variable into register number 1.</td>
 * </tr>
 * <tr>
 * <td>LoadArguments</td>
 * <td>Pre-load the <em>parent</em> variable into register number 2.</td>
 * </tr>
 * <tr>
 * <td>LoadSuper</td>
 * <td>Pre-load the <em>super</em> variable into register number 3.</td>
 * </tr>
 * <tr>
 * <td>LoadRoot</td>
 * <td>Pre-load the <em>_root</em> variable into register number 4.</td>
 * </tr>
 * <tr>
 * <td>LoadParent</td>
 * <td>Pre-load the <em>_parent</em> variable into register number 5.</td>
 * </tr>
 * <tr>
 * <td>LoadGlobal</td>
 * <td>Pre-load the <em>_global</em> variable into register number 5.</td>
 * </tr>
 * </table>
 * 
 * <p>
 * The register numbers that the predefined variables, <em>this</em>,
 * <em>parent</em>, <em>super</em>, <em>_root</em>, <em>_parent</em>
 * and <em>_global</em> are assigned to are fixed. When specifying which of
 * the functions arguments are also assigned to registers it is important avoid
 * these locations otherwise the variables will be overwritten.
 * </p>
 * 
 * <p>
 * User-defined functions are also used to create methods for user-defined
 * objects. The name of the function is omitted and the function definition is
 * assigned to a variable which allows it to be referenced at a alter time. See
 * the example below.
 * </p>
 * 
 * <p>
 * The arguments supplied to the function can be referenced by the name supplied
 * in the arguments array.
 * </p>
 * 
 * <p>
 * All the action objects added are owned by the function. They will be deleted
 * when the function definition is deleted.
 * </p>
 * 
 * <h1 class="datasheet">Examples</h1>
 * 
 * <p>
 * 1. Define a function<br/> Define a function that increments the value passed
 * to it:
 * </p>
 * 
 * <pre>
 * // List the names of the arguments
 * 
 * ArrayList arguments = new ArrayList();
 * 
 * arguments.add(&quot;value&quot;);
 * 
 * // Now define the actions performed by the function. Values passed to the function
 * // can be referenced by the name defined in the array of arguments.
 * 
 * ArrayList actions = new ArrayList();
 * 
 * actions.add(new FSPush(&quot;value&quot;));
 * actions.add(FSAction.GetVariable());
 * actions.add(new FSPush(1));
 * actions.add(FSAction.Add());
 * actions.add(FSAction.Return());
 * actions.add(new FSNewFunction2(&quot;increment&quot;, arguments, actions));
 * </pre>
 * 
 * <p>
 * The function can then be referenced using it's name:
 * </p>
 * 
 * <pre>
 * actions.add(new FSPush(1));
 * actions.add(new FSPush(&quot;increment&quot;));
 * actions.add(FSAction.ExecuteFunction());
 * </pre>
 * 
 * <p>
 * 2. Defining a method.<br/> When creating a user-defined object the name of
 * the function can be omitted. Simply assign the function definition to a
 * variable:
 * </p>
 * 
 * <pre>
 *  actions.add(new FSPush(methodVariable));
 * 
 *  FSVector&lt;FSString&gt; arguments;
 * 
 *  arguments.push_back(&quot;value&quot;);
 * 
 *  ArrayList actions = new ArrayList();
 * 
 *  actions.add(new FSPush(&quot;value&quot;));
 *  actions.add(FSAction.GetVariable());
 *  actions.add(new FSPush(1));
 *  actions.add(FSAction.Add());
 *  actions.add(FSAction.Return());
 *  actions.add(new FSNewFunction2(arguments, actions));
 *  actions.add(FSAction.SetVariable()));
 * </pre>
 * 
 * <p>
 * The function can then be executed by pushing the arguments onto the stack
 * then calling the function assigned to the variable:
 * </p>
 * 
 * <pre>
 * // Push argument(s) onto stack
 * 
 * actions.add(new FSPush(1));
 * 
 * // Get the variable that contains the function
 * 
 * actions.add(new FSPush(methodVariable));
 * actions.add(FSAction.GetVariable());
 * 
 * // Execute the function
 * actions.add(FSAction.ExecuteMethod());
 * </pre>
 * 
 * <p>
 * 3. Controlling the execution environment.<br/> The code that defines the
 * optimizations that improve execution performance is created by bitwise-ORing
 * the individual flags together.
 * </p>
 * 
 * <pre>
 * int optimizations = FSNewFunction2.CreateSuper | FSNewFunction2.PreloadSuper;
 * </pre>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSNewFunction class represents the ActionDefineFunction2 action of the
 * Macromedia Flash (SWF) File Format Specification. It was introduced in Flash
 * 7.
 * </p>
 */
public class FSNewFunction2 extends FSActionObject
{
	/** Create and initialized the predefined variable, <em>super</em>. */
	public static final int CreateSuper = 4;

	/** Create and initialized the predefined variable, <em>arguments</em>. */
	public static final int CreateArguments = 16;

	/** Create and initialized the predefined variable, <em>this</em>. */
	public static final int CreateThis = 64;

	/** Load the predefine variable, <em>this</em>, into register 1. */
	public static final int LoadThis = 128;

	/** Load the predefine variable, <em>arguments</em>, into register 2. */
	public static final int LoadArguments = 32;

	/** Load the predefine variable, <em>super</em>, into register 3. */
	public static final int LoadSuper = 8;

	/** Load the predefine variable, <em>_root</em>, into register 4. */
	public static final int LoadRoot = 2;

	/** Load the predefine variable, <em>_parent</em>, into register 5. */
	public static final int LoadParent = 1;

	/** Load the predefine variable, <em>_global</em>, into register 6. */
	public static final int LoadGlobal = 32768;

	private String name = null;
	private int registerCount = 0;
	private int optimizations = 0;
	private ArrayList arguments = null;
	private ArrayList actions = null;

	/*
	 * variables used to record state when encoding.
	 */
	private int _actionsLength = 0;

	/**
	 * Construct an FSNewFunction2 object, initialising it with values decoded
	 * from an encoded object.
	 * 
	 * @param coder
	 *            an FSCoder containing the binary data.
	 */
	public FSNewFunction2(FSCoder coder)
	{
		super(NewFunction2);
		decode(coder);
	}

	/**
	 * Constructs an FSNewFunction with the specified name, argument names and
	 * actions to be executed. The order of the Strings in the argument array
	 * indicate the order in which the values will be popped off the stack when
	 * the function is executed. The first argument is popped from the stack
	 * first.
	 * 
	 * @param name
	 *            the name of the function.
	 * @param arguments
	 *            an array of Strings listing the names of the arguments.
	 * @param actions
	 *            the array of actions that define the operation performed by
	 *            the function.
	 */
	public FSNewFunction2(String name, ArrayList arguments, ArrayList actions)
	{
		super(NewFunction2);
		setName(name);
		setArguments(arguments);
		setActions(actions);
	}

	/**
	 * Constructs an anonymous FSNewFunction with the specified argument names
	 * and actions to be executed. Use this constructor when defining functions
	 * that will be assigned to object variables and used as methods.
	 * 
	 * @param arguments
	 *            an array of Strings listing the names of the arguments.
	 * @param actions
	 *            the array of actions that define the operation performed by
	 *            the function.
	 */
	public FSNewFunction2(ArrayList arguments, ArrayList actions)
	{
		super(NewFunction2);
		setArguments(arguments);
		setActions(actions);
	}

	/**
	 * Constructs an FSNewFunction2 object by copying values from an existing
	 * object.
	 * 
	 * @param obj
	 *            an FSNewFunction2 object.
	 */
	public FSNewFunction2(FSNewFunction2 obj)
	{
		super(obj);

		if (obj.name != null)
			name = new String(obj.name);

		registerCount = obj.registerCount;
		optimizations = obj.optimizations;

		if (obj.arguments != null)
		{
			arguments = new ArrayList(obj.arguments.size());

			for (Iterator i = obj.arguments.iterator(); i.hasNext();)
				arguments.add(new String(i.next().toString()));
		}

		if (obj.actions != null)
		{
			actions = new ArrayList(obj.actions.size());

			for (Iterator i = obj.actions.iterator(); i.hasNext();)
				actions.add(((FSActionObject) i.next()).clone());
		}
	}

	/**
	 * Adds the name of an argument to the array of argument names.
	 * 
	 * @param anArgument
	 *            the name of an argument passed to the FSNewFunction object.
	 */
	public void add(FSRegisterVariable anArgument)
	{
		arguments.add(anArgument);
	}

	/**
	 * Adds the action object to the array of actions.
	 * 
	 * @param anAction
	 *            an object belonging to a class derived from FSActionObject.
	 */
	public void add(FSActionObject anAction)
	{
		actions.add(anAction);
	}

	/**
	 * Gets the name of the function.
	 * 
	 * @return the name of the function.
	 */
	public String getName()
	{
		return name;
	}

	/**
	 * Sets the name of the function. The name may be null when defining
	 * methods.
	 * 
	 * @param aString
	 *            the name of the function or null for a method.
	 */
	public void setName(String aString)
	{
		name = aString;
	}

	/**
	 * Gets the number of registers to allocate for function variables.
	 * 
	 * @return the number of registers to allocate.
	 */
	public int getRegisterCount()
	{
		return registerCount;
	}

	/**
	 * Sets the number of registers to allocate for function variables. Up to
	 * 256 registers may be allocated for each function.
	 * 
	 * @param count
	 *            the number of registers to allocate.
	 */
	public void setRegisterCount(int count)
	{
		registerCount = count;
	}

	/**
	 * Get the code containing the compound flags that control the execution
	 * environment of the function or method.
	 * 
	 * @return the code for the optimizations.
	 */
	public int getOptimizations()
	{
		return optimizations;
	}

	/**
	 * Set the code containing the compound flags that control the execution
	 * environment of the function or method.
	 * 
	 * @param code
	 *            the compound code can be created by bitwise-ORing the
	 *            constants that identify the optimizations performed.
	 */
	public void setOptimizations(int code)
	{
		optimizations = code;
	}

	/**
	 * Gets the array of FSRegisterVariables that define the function arguments
	 * and whether they are assigned to internal registers or to local variables
	 * in memory.
	 * 
	 * @return the array of FSRegisterVariables that define the functions
	 *         arguments.
	 */
	public ArrayList getArguments()
	{
		return arguments;
	}

	/**
	 * Sets the array of FSRegisterVariables that define the function arguments
	 * and whether they are assigned to internal registers or to local variables
	 * in memory.
	 * 
	 * @param anArray
	 *            an array of Strings listing the names of the arguments.
	 */
	public void setArguments(ArrayList anArray)
	{
		arguments = anArray;
	}

	/**
	 * Gets the actions executed by the function.
	 * 
	 * @return the array of actions executed.
	 */
	public ArrayList getActions()
	{
		return actions;
	}

	/**
	 * Sets the actions.
	 * 
	 * @param anArray
	 *            the array of actions that define the operation performed by
	 *            the function.
	 */
	public void setActions(ArrayList anArray)
	{
		actions = anArray;
	}

	public Object clone()
	{
		FSNewFunction2 anObject = (FSNewFunction2) super.clone();

		anObject.arguments = new ArrayList();

		for (Iterator i = arguments.iterator(); i.hasNext();)
			anObject.arguments.add((FSRegisterVariable) ((FSRegisterVariable) i
							.next()).clone());

		anObject.actions = new ArrayList();

		for (Iterator i = actions.iterator(); i.hasNext();)
			anObject.actions.add(((FSActionObject) i.next()).clone());

		return anObject;
	}

	public boolean equals(Object anObject)
	{
		boolean result = false;

		if (super.equals(anObject))
		{
			FSNewFunction2 typedObject = (FSNewFunction2) anObject;

			if (name != null)
				result = name.equals(typedObject.name);
			else
				result = name == typedObject.name;

			result = result && registerCount == typedObject.registerCount;
			result = result && optimizations == typedObject.optimizations;

			if (arguments != null)
				result = result && arguments.equals(typedObject.arguments);
			else
				result = result && arguments == typedObject.arguments;

			if (actions != null)
				result = result && actions.equals(typedObject.actions);
			else
				result = result && actions == typedObject.actions;
		}
		return result;
	}

	public void appendDescription(StringBuffer buffer, int depth)
	{
		buffer.append(name());

		if (depth > 0)
		{
			buffer.append(": { ");
			Transform.append(buffer, "name", name);
			Transform.append(buffer, "registerCount", registerCount);
			Transform.append(buffer, "optimizations", optimizations);
			Transform.append(buffer, "arguments", arguments, depth);
			Transform.append(buffer, "actions", actions, depth);
			buffer.append("}");
		}
	}

	public int length(FSCoder coder)
	{
		super.length(coder);

		length += (name != null) ? coder.strlen(name, true) : 1;
		length += 5;

		for (int i = 0; i < arguments.size(); i++)
			length += ((FSRegisterVariable) arguments.get(i)).length(coder);

		length += 2;

		_actionsLength = 0;

		for (Iterator i = actions.iterator(); i.hasNext();)
		{
			FSActionObject currentAction = (FSActionObject) i.next();

			_actionsLength += currentAction.length(coder);
			_actionsLength += (currentAction.getType() > 128) ? 3 : 1;
		}
		length += _actionsLength;

		return length;
	}

	public void encode(FSCoder coder)
	{
		coder.beginObject(name());

		coder.writeWord(type, 1);
		coder.writeWord(length - _actionsLength, 2);

		if (name != null)
			coder.writeString(name);

		coder.writeWord(0, 1);

		coder.writeWord(arguments.size(), 2);
		coder.writeWord(registerCount, 1);
		coder.writeBits(optimizations, 16);

		for (Iterator i = arguments.iterator(); i.hasNext();)
			((FSRegisterVariable) i.next()).encode(coder);

		coder.writeWord(_actionsLength, 2);

		for (Iterator i = actions.iterator(); i.hasNext();)
		{
			FSActionObject action = (FSActionObject) i.next();

			int objStart = coder.getPointer();
			int start = coder.getPointer()
							+ ((action.getType() > 128) ? 24 : 8);
			int next = start + (action.getLength() << 3);

			action.encode(coder);
			coder.setPointer(next);

			int delta = (coder.getPointer() - next) >> 3;

			if (delta != 0)
			{
				coder.context[FSCoder.CodingError] = 1;
				coder.context[FSCoder.TypeInError] = action.getType();
				coder.context[FSCoder.StartOfError] = objStart >>> 3;
				coder.context[FSCoder.ExpectedLength] = (next - objStart) >>> 3;
				coder.context[FSCoder.Delta] = delta;
			}
		}

		coder.endObject(name());
	}

	public void decode(FSCoder coder)
	{
		int argumentCount = 0;
		int bytesRead = 0;

		arguments = new ArrayList();
		actions = new ArrayList();

		super.decode(coder);

		name = coder.readString();

		argumentCount = coder.readWord(2, false);
		registerCount = coder.readWord(1, false);
		optimizations = coder.readBits(16, false);

		for (int i = 0; i < argumentCount; i++)
			arguments.add(new FSRegisterVariable(coder));

		_actionsLength = coder.readWord(2, false);
		length += _actionsLength;

		while (bytesRead < _actionsLength)
		{
			FSActionObject anAction = FSMovie.decodeAction(coder);

			bytesRead += anAction.getLength()
							+ ((anAction.getType() >= 128) ? 3 : 1);
			actions.add(anAction);
		}

		coder.endObject(name());
	}
}
