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

/**
 * FSInitialize is used to specify a sequence of actions that are executed to
 * initialise a movie clip before it is displayed.
 * 
 * <p>
 * It implements the #initclip pragma in the ActionScript language.
 * </p>
 * 
 * <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>identifier</td>
 * <td>The identifier of the FSDefineMovieClip object that defines the movie
 * clip.</td>
 * </tr>
 * 
 * <tr>
 * <td>actions</td>
 * <td>An array of actions that will be executed to initialize the movie clips.</td>
 * </tr>
 * 
 * </table>
 * 
 * <p>
 * Unlike the FSDoAction class which specifies the actions that are executed
 * when a particular frame is displayed the actions contained in an FSInitialize
 * object are executed only once, regardless of where the object is included in
 * a movie. If a frame containing the FSInitialize object is played again the
 * actions are skipped. Also there can only be one FSInitialize object for each
 * movie clip defined in the movie.
 * </p>
 * 
 * <h1 class="datasheet">Examples</h1>
 * 
 * <pre>
 *  ArrayList actions = new ArrayList();
 * 
 *  actions.add(new FSPush(&quot;_root&quot;));
 *  actions.add(FSAction.GetVariable());
 * 
 *  int clipId = movie.newIdentifier();
 * 
 *  movie.add(new FSDefineMovieClip(clipId, clipObjects));
 *  ...
 * 
 *  movie.add(new FSInitialize(clipId, actions));
 *  ...
 *  movie.add(new FSShowFrame()); 
 * </pre>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSInitialize class represents the DoInitAction tag from the Macromedia
 * Flash (SWF) File Format Specification. It was introduced in Flash 6.
 * </p>
 * 
 * @see FSDoAction
 */
public class FSInitialize extends FSMovieObject
{
	private int identifier = 0;
	private ArrayList actions = null;
	private byte[] encodedActions = null;

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

	/**
	 * Constructs an FSInitialize object that will initialize the movie clip
	 * with the specified identifier with the actions in the array.
	 * 
	 * @param anIdentifier
	 *            the identifier of the movie clip to initialize
	 * @param anArray
	 *            the array of action objects.
	 */
	public FSInitialize(int anIdentifier, ArrayList anArray)
	{
		super(Initialize);
		setIdentifier(anIdentifier);
		setActions(anArray);
	}

	/**
	 * Constructs an FSInitialize object that will initialize the movie clip
	 * with the specified identifier with the encoded actions.
	 * 
	 * @param anIdentifier
	 *            the identifier of the movie clip to initialize
	 * @param bytes
	 *            an array of encoded action objects.
	 */
	public FSInitialize(int anIdentifier, byte[] bytes)
	{
		super(Initialize);
		setIdentifier(anIdentifier);
		setEncodedActions(bytes);
	}

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

		identifier = obj.identifier;

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

	/**
	 * Returns the identifier of the movie clip that will be initialized.
	 * 
	 * @return the identifier of the movie clip.
	 */
	public int getIdentifier()
	{
		return identifier;
	}

	/**
	 * Sets the identifier of the movie clip that will be initialized.
	 * 
	 * @param aNumber
	 *            the identifier of the movie clip. The value must be in the
	 *            range 1..65535.
	 */
	public void setIdentifier(int aNumber)
	{
		identifier = aNumber;
	}

	/**
	 * 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)
	{
		if (encodedActions != null)
		{
			actions = FSMovie.decodeActions(encodedActions);
			encodedActions = null;
		}
		actions.add(anAction);
	}

	/**
	 * Get the array of actions that are used to initialize the movie clip.
	 * 
	 * @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 of the movie clip that will be initialized
	 * 
	 * @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()
	{
		FSInitialize anObject = (FSInitialize) 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))
		{
			FSInitialize typedObject = (FSInitialize) anObject;

			result = identifier == typedObject.identifier;

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

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

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

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

			buffer.append("}");
		}
	}

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

		length += 2;

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

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

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

			if ((actions.size() == 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);

		coder.writeWord(identifier, 2);

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

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

				int objStart = coder.getPointer();
				int length = action.getLength();
				int start = coder.getPointer()
								+ ((action.getType() > 128) ? 24 : 8);
				int next = start + (length << 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;
				}
			}

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

		identifier = coder.readWord(2, false);

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

			int len = length - 2;
			int start;

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

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