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

/**
 * FSDefineButton defines the appearance of a button and the actions performed
 * when the button is clicked.
 * 
 * <table class="datasheet">
 * 
 * <tr>
 * <th align="left" colspan="2">Attributes</th>
 * </tr>
 * 
 * <tr>
 * <td>type</td>
 * <td>Identifies the action when it is encoded. Read-only.</td>
 * </tr>
 * <tr>
 * <td>identifier</td>
 * <td>An unique identifier for this object, in the range 1..65535.</td>
 * </tr>
 * 
 * <tr>
 * <td>buttonRecords</td>
 * <td>an array of FSButton objects that define the appearance of the button in
 * each of its states. The array must contain at least one FSButton object.</td>
 * </tr>
 * 
 * <tr>
 * <td>actions</td>
 * <td>an array of action objects that are executed when the button is clicked.</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>
 * A FSDefineButton object must contain at least one FSButton object. If more
 * than one button record is defined for a given button state then each shape
 * will be displayed by the button. The order in which the shapes are displayed
 * is determined by the layer assigned to each FSButton object.
 * </P>
 * 
 * <h1 class="datasheet">Examples</h1>
 * 
 * <p>
 * 1. Define a simple button that highlights itself when the mouse is move over
 * it. No actions are performed when the button is clicked.
 * </p>
 * 
 * <pre>
 * FSDefineShape normal = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, shape);
 * FSDefineShape highlight = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, highlightShape);
 * 
 * ArrayList records = new ArrayList();
 * ArrayList actions = new ArrayList();
 * 
 * records.add(new FSButton(FSButton.Up, normal.getIdentifier(), 1));
 * records.add(new FSButton(FSButton.Over, highlight.getIdentifier(), 2));
 * 
 * FSDefineButton button = new FSDefineButton(movie.newIdentifier(), records,
 * 				actions);
 * </pre>
 * 
 * <p>
 * 2. Define a "complex" button that highlights itself when the mouse is move
 * over it and actions are executed when the button is clicked.
 * </p>
 * 
 * <pre>
 * FSDefineShape upShape = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, shape1);
 * FSDefineShape overShape = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, shape2);
 * FSDefineShape downShape = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, shape3);
 * 
 * ArrayList records = new ArrayList();
 * records.add(new FSButton(FSButton.Up, upShape.getIdentifier(), 1));
 * records.add(new FSButton(FSButton.Over, overShape.getIdentifier(), 2));
 * records.add(new FSButton(FSButton.Down, downShape.getIdentifier(), 3));
 * 
 * ArrayList actions = new ArrayList();
 * 
 * actions.add(action);
 * actions.add(action);
 * actions.add(action);
 * 
 * FSDefineButton button = new FSDefineButton(movie.newIdentifier(), records,
 * 				actions);
 * </pre>
 * 
 * <p>
 * 3. If more than one button record is defined for a state then the layer
 * number defines the order the shapes are displayed. This allows buttons to be
 * "reused" with only the label on the button being changed.
 * </p>
 * 
 * <pre>
 * FSDefineShape upShape = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, shape1);
 * FSDefineShape overShape = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, shape2);
 * FSDefineShape downShape = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, shape3);
 * 
 * // The label shape contains the &quot;text&quot; for the button. Note the text must be 
 * // drawn as a shape.
 * 
 * FSDefineShape label = new FSDefineShape(movie.newIdentifier(), bounds,
 * 				lineStyles, fillStyles, shape4);
 * 
 * ArrayList records = new ArrayList();
 * 
 * // Note that the label defined for all of the button's states. This ensures the 
 * // label is visible at all times when the mouse is moved over the button.
 * 
 * records.add(FSButton(FSButton.Up, upShape.getIdentifier(), 1));
 * records.add(FSButton(FSButton.Up, label.getIdentifier(), 2));
 * records.add(FSButton(FSButton.Over, overShape.getIdentifier(), 3));
 * records.add(FSButton(FSButton.Over, label.getIdentifier(), 4));
 * records.add(FSButton(FSButton.Down, downShape.getIdentifier(), 5));
 * records.add(FSButton(FSButton.Down, label.getIdentifier(), 6));
 * 
 * ArrayList actions = new ArrayList();
 * 
 * actions.add(action);
 * actions.add(action);
 * actions.add(action);
 * 
 * FSDefineButton button = new FSDefineButton(movie.newIdentifier(), records,
 * 				actions);
 * </pre>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSDefineButton class represents the DefineButton structure from the
 * Macromedia Flash (SWF) File Format Specification. It was introduced in Flash
 * 1.
 * </p>
 */
public class FSDefineButton extends FSDefineObject
{
	private ArrayList buttonRecords = null;
	private ArrayList actions = null;
	private byte[] encodedActions = null;

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

	/**
	 * Constructs an FSDefineButton object with the identifier, button records
	 * and actions.
	 * 
	 * @param anIdentifier
	 *            a unique identifier for this button.
	 * @param buttonRecordArray
	 *            an array of FSButton objects.
	 * @param actionArray
	 *            and array of action objects.
	 */
	public FSDefineButton(int anIdentifier, ArrayList buttonRecordArray, ArrayList actionArray)
	{
		super(DefineButton, anIdentifier);
		setButtonRecords(buttonRecordArray);
		setActions(actionArray);
	}

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

		buttonRecords = new ArrayList();

		for (Iterator i = obj.buttonRecords.iterator(); i.hasNext();)
			buttonRecords.add(((FSButton) i.next()).clone());

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

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

	/**
	 * Constructs an FSDefineButton object with the identifier, button records
	 * and encoded actions.
	 * 
	 * @param anIdentifier
	 *            a unique identifier for this button.
	 * @param buttonRecordArray
	 *            an array of FSButton objects.
	 * @param bytes
	 *            an array of encoded action objects.
	 */
	public FSDefineButton(int anIdentifier, ArrayList buttonRecordArray,
							byte[] bytes)
	{
		super(DefineButton, anIdentifier);
		setButtonRecords(buttonRecordArray);
		setEncodedActions(bytes);
	}

	/**
	 * Adds the button record object to the array of button records.
	 * 
	 * @param aButtonRecord
	 *            an FSButton object.
	 */
	public void add(FSButton aButtonRecord)
	{
		buttonRecords.add(aButtonRecord);
	}

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

	/**
	 * Gets the array of button records defined for this button.
	 * 
	 * @return the array of FSButton objects defined for this button.
	 */
	public ArrayList getButtonRecords()
	{
		return buttonRecords;
	}

	/**
	 * Gets the array of actions that will be executed when the button is
	 * clicked and released.
	 * 
	 * @return the array of action objects defined for this button.
	 */
	public ArrayList getActions()
	{
		if (encodedActions != null)
		{
			actions = FSMovie.decodeActions(encodedActions);
			encodedActions = null;
		}
		return actions;
	}

	/**
	 * Sets the array of button records defined for this button.
	 * 
	 * @param anArray
	 *            an array of FSButton objects.
	 */
	public void setButtonRecords(ArrayList anArray)
	{
		buttonRecords = anArray;
	}

	/**
	 * Sets the array of actions that will be executed when the button is
	 * clicked and released.
	 * 
	 * @param anArray
	 *            and 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 that will be executed when the button is
	 * clicked and released. The encoded actions are typically 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()
	{
		FSDefineButton anObject = (FSDefineButton) super.clone();

		anObject.buttonRecords = new ArrayList();

		for (Iterator i = buttonRecords.iterator(); i.hasNext();)
			anObject.buttonRecords.add(((FSButton) i.next()).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))
		{
			FSDefineButton typedObject = (FSDefineButton) anObject;

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

			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(": { ");
			Transform.append(buffer, "buttonRecords", buttonRecords, depth);

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

			buffer.append("}");
		}
	}

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

		for (Iterator buttonIterator = buttonRecords.iterator(); buttonIterator
						.hasNext();)
			length += ((FSTransformObject) buttonIterator.next()).length(coder);

		length += 1;

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

		for (Iterator buttonIterator = buttonRecords.iterator(); buttonIterator
						.hasNext();)
			((FSTransformObject) buttonIterator.next()).encode(coder);

		coder.writeWord(0, 1);

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

		int start = coder.getPointer() - 16;

		buttonRecords = new ArrayList();

		while (coder.scanWord(1, false) != 0)
			buttonRecords.add(new FSButton(coder));

		coder.readWord(1, false); // character end

		int actionsLength = length - ((coder.getPointer() - start) >>> 3);

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

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

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