/*
 * FSDoAction.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.*;

/**
 * FSDoAction is used to specify a sequence of actions that are executed when a
 * frame is displayed.
 * 
 * <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. Read-only.</td>
 * </tr>
 * 
 * <tr>
 * <td>actions</td>
 * <td>An array of FSActionObjects which are executed by the Flash Player when
 * the current frame is displayed. The actions are executed in the order they
 * appear in the array.</td>
 * </tr>
 * 
 * <tr>
 * <td>encodedActions</td>
 * <td>An array of bytes containing encoded actions can also be set. The
 * encoded actions are typically generated by the parser in the Translate
 * framework. The actions array and encodedActions cannot both be valid at the
 * same time. Accessor methods used to set either of the attributes will set the
 * other to null.</td>
 * </tr>
 * 
 * </table>
 * 
 * <p>
 * To define the actions for a given frame the FSDoAction object should be added
 * to a movie after the previous frame is displayed but before the FSShowFrame
 * object that displays the 'current' frame and triggers the actions to be
 * executed.
 * </p>
 * 
 * <p>
 * Only one FSDoAction object can be used to specify the actions for a given
 * frame. If more than one FSDoAction object is added in a single frame only the
 * actions contained in the last FSDoAction object (before the FSShowFrame
 * object) will be executed when the frame is displayed. The other FSDoAction
 * objects will be ignored.
 * </p>
 * 
 * <h1 class="datasheet">Examples</h1>
 * 
 * <pre>
 *  ArrayList actions = new ArrayList();
 * 
 *  actions.add(new FSPush(&quot;_root&quot;));
 *  actions.add(new FSAction(FSAction.GetVariable));
 *  ...
 * 
 *  movie.add(new FSShowFrame()); // previous frame
 *  ...
 * 
 *  movie.add(new FSDoAction(actions));
 *  movie.add(new FSShowFrame()); // frame where actions will be executed
 * </pre>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSDoAction class represents the DoAction tag from the Macromedia Flash
 * (SWF) File Format Specification. It was introduced in Flash 1.
 * </p>
 */
public class FSDoAction extends FSMovieObject
{
	private ArrayList actions = null;

	private byte[] encodedActions = null;

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

	/**
	 * Constructs an FSDoAction object with an array of actions.
	 * 
	 * @param anArray
	 *            the array of action objects.
	 */
	public FSDoAction(ArrayList anArray)
	{
		super(FSMovieObject.DoAction);
		setActions(anArray);
	}

	/**
	 * Constructs an FSDoAction object with an array of encoded actions
	 * generated by the classes in Translate.
	 * 
	 * @param bytes
	 *            an array of encoded action objects.
	 */
	public FSDoAction(byte[] bytes)
	{
		super(FSMovieObject.DoAction);
		setEncodedActions(bytes);
	}

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

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

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

	/**
	 * Adds the action object to the array of actions. If the object already
	 * contains encoded actions then they will be deleted.
	 * 
	 * @param anAction
	 *            an object belonging to a class derived from FSActionObject.
	 */
	public void add(FSActionObject anAction)
	{
		if (encodedActions != null)
		{
			actions = FSMovie.decodeActions(encodedActions);
			encodedActions = null;
		}
		actions.add(anAction);
	}

	/**
	 * Get the array of actions that are executed when the frame is displayed.
	 * 
	 * @return the array of action objects.
	 */
	public ArrayList getActions()
	{
		if (encodedActions != null)
		{
			actions = FSMovie.decodeActions(encodedActions);
			encodedActions = null;
		}
		return actions;
	}

	/**
	 * Set the array of actions that will be executed when the next ShowFrame
	 * tag is executed by the Flash Player. If the object already contains
	 * encoded actions then they will be deleted.
	 * 
	 * @param anArray
	 *            the array of action objects.
	 */
	public void setActions(ArrayList anArray)
	{
		actions = anArray;
		encodedActions = null;
	}

	/**
	 * Get the array of encoded actions that are executed when the frame is
	 * displayed.
	 * 
	 * @return the array of action objects or null if the actions have been
	 *         decoded.
	 */
	public byte[] getEncodedActions()
	{
		return encodedActions;
	}

	/**
	 * Set the array of encoded actions generated by the classes in the
	 * Translate framework. If the object already contains an array of actions
	 * then they will be deleted.
	 * 
	 * @param bytes
	 *            the array of encoded actions.
	 */
	public void setEncodedActions(byte[] bytes)
	{
		encodedActions = bytes;
		actions = null;
	}

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

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

			for (Iterator i = actions.iterator(); i.hasNext();)
				anObject.actions.add(((FSActionObject) i.next()).clone());
		} else
		{
			anObject.encodedActions = Transform.clone(encodedActions);
		}
		return anObject;
	}

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

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

			if (actions != null)
			{
				result = actions.equals(typedObject.actions);
			} else
			{
				result = Transform.equals(encodedActions,
								typedObject.encodedActions);
			}
		}
		return result;
	}

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

		if (depth > 0)
		{
			buffer.append(": { ");

			if (actions != null)
				Transform.append(buffer, "actions", actions, depth);
			else
				buffer.append("actions = <data>; ");

			buffer.append("}");
		}
	}

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

		if (actions != null)
		{
			FSActionObject currentAction = null;
			int count = actions.size();

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

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

			if (count == 0 || (currentAction.getType() != FSAction.End))
			{
				length += 1;
			}
		} else
		{
			length += encodedActions.length;

			if ((encodedActions.length == 0)
							|| (encodedActions[encodedActions.length - 1] != FSAction.End))
			{
				length += 1;
			}
		}
		return length;
	}

	public void encode(FSCoder coder)
	{
		super.encode(coder);

		if (actions != null)
		{
			FSActionObject action = null;

			for (Iterator i = actions.iterator(); i.hasNext();)
			{
				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);

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

			if ((actions.size() == 0) || (action.getType() != FSAction.End))
			{
				coder.writeWord(0, 1);
			}
		} else
		{
			coder.writeBytes(encodedActions);

			if ((encodedActions.length == 0)
							|| (encodedActions[encodedActions.length - 1] != FSAction.End))
			{
				coder.writeWord(0, 1);
			}
		}
		coder.endObject(name());
	}

	public void decode(FSCoder coder)
	{
		super.decode(coder);

		if (coder.context[FSCoder.DecodeActions] == 1)
		{
			actions = new ArrayList();

			int len = length;
			int start;

			while (len > 0)
			{
				start = coder.getPointer();

				actions.add(FSMovie.decodeAction(coder));
				len -= (coder.getPointer() - start) >>> 3;
			}
		} else
		{
			encodedActions = new byte[length];
			coder.readBytes(encodedActions);
		}
		coder.endObject(name());
	}
}