/*
 * FSNewFunction.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 FSNewFunction action is used to create a user-defined function.
 * 
 * <table class="datasheet">
 * 
 * <tr>
 * <th align="left" colspan="2">Attributes</th>
 * </tr>
 * 
 * <tr>
 * <td>type</td>
 * <td>Identifies the data structure when it is encoded. The type attribute is
 * read-only and may be used when iterating through an array of FSActionObjects
 * to identify the object class without using run-time type checking.</td>
 * </tr>
 * 
 * <tr>
 * <td>name</td>
 * <td>A string defining the name of the function.</td>
 * </tr>
 * 
 * <tr>
 * <td>arguments</td>
 * <td>An array containing the names of the arguments. 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 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>
 * 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 FSNewFunction(&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 FSNewFunction(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.ExecuteFunction());
 * </pre>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSNewFunction class represents the ActionDefineFunction action of the
 * Macromedia Flash (SWF) File Format Specification. It was introduced in Flash
 * 5.
 * </p>
 */
public class FSNewFunction extends FSActionObject
{
	private String name = null;
	private ArrayList arguments = null;
	private ArrayList actions = null;

	private int actionsLength = 0;

	FSNewFunction()
	{
		super(NewFunction);
	}

	/**
	 * Construct an FSNewFunction object, initialising it with values decoded
	 * from an encoded object.
	 * 
	 * @param coder
	 *            an FSCoder containing the binary data.
	 */
	public FSNewFunction(FSCoder coder)
	{
		super(NewFunction);
		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 fist argument is popped from the stack
	 * first.
	 * 
	 * @param aString
	 *            the name of the function.
	 * @param argumentArray
	 *            an array of Strings listing the names of the arguments.
	 * @param actionArray
	 *            the array of actions that define the operation performed by
	 *            the function.
	 */
	public FSNewFunction(String aString, ArrayList argumentArray,
							ArrayList actionArray)
	{
		super(NewFunction);
		setName(aString);
		setArguments(argumentArray);
		setActions(actionArray);
	}

	/**
	 * 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 argumentArray
	 *            an array of Strings listing the names of the arguments.
	 * @param actionArray
	 *            the array of actions that define the operation performed by
	 *            the function.
	 */
	public FSNewFunction(ArrayList argumentArray, ArrayList actionArray)
	{
		super(NewFunction);
		setArguments(argumentArray);
		setActions(actionArray);
	}

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

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

		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(String 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;
	}

	/**
	 * Gets the names of the function arguments.
	 * 
	 * @return the array of argument names.
	 */
	public ArrayList getArguments()
	{
		return arguments;
	}

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

	/**
	 * Sets the name of the function.
	 * 
	 * @param aString
	 *            the name of the function.
	 */
	public void setName(String aString)
	{
		name = aString;
	}

	/**
	 * Sets the names of the function arguments.
	 * 
	 * @param anArray
	 *            an array of Strings listing the names of the arguments.
	 */
	public void setArguments(ArrayList anArray)
	{
		arguments = anArray;
	}

	/**
	 * 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()
	{
		FSNewFunction anObject = (FSNewFunction) super.clone();

		anObject.arguments = new ArrayList();

		for (Iterator i = arguments.iterator(); i.hasNext();)
			anObject.arguments.add(new String((String) i.next()));

		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))
		{
			FSNewFunction typedObject = (FSNewFunction) anObject;

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

			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, "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 += 2;

		if (arguments.size() > 0)
		{
			for (int i = 0; i < arguments.size(); i++)
				length += coder.strlen((String) arguments.get(i), true);
		}

		length += 2;

		actionsLength = 0;

		for (int i = 0; i < actions.size(); i++)
		{
			FSActionObject currentAction = (FSActionObject) actions.get(i);

			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);

		if (arguments.size() > 0)
		{
			for (int i = 0; i < arguments.size(); i++)
			{
				coder.writeString((String) arguments.get(i));
				coder.writeWord(0, 1);
			}
		}

		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);

		if (argumentCount > 0)
		{
			for (int i = argumentCount; i > 0; i--)
				arguments.add(coder.readString());
		}

		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());
	}
}
