/*
 * FSButtonEvent.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.List;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * FSButtonEvent is used to define the actions that a button will execute in
 * response to a particular event.
 * 
 * <p>
 * The events that a button responds to are:
 * </p>
 * 
 * <table class="datasheet">
 * <tr>
 * <td>RollOver</td>
 * <td>occurs when the mouse cursor moves over the active area of a button.</td>
 * </tr>
 * <tr>
 * <td>RollOut</td>
 * <td>occurs when the mouse cursor moves out of the active area of a button.</td>
 * </tr>
 * <tr>
 * <td>Press</td>
 * <td>occurs when the mouse button is clicked while the mouse cursor is over
 * the active area of the button.</td>
 * </tr>
 * <tr>
 * <td>Release</td>
 * <td>occurs when the mouse button is clicked and released while the mouse
 * cursor is over the active area of the button.</td>
 * </tr>
 * <tr>
 * <td>DragOut</td>
 * <td>occurs when the mouse button is clicked and the mouse cursor is dragged
 * out of the active area of the button.</td>
 * </tr>
 * <tr>
 * <td>DragOver</td>
 * <td>occurs when the mouse button is clicked, the mouse cursor is dragged
 * into the active area of the button and the mouse button is released.</td>
 * </tr>
 * </td>
 * </tr>
 * </table>
 * 
 * <p>
 * When a button is configured as a menu item (FSDefineButton2 objects only)
 * then three additional events can occur:
 * </p>
 * 
 * <table class="datasheet">
 * <tr>
 * <td>MenuDragOver</td>
 * <td>occurs when the mouse button is clicked and the mouse cursor is dragged
 * into the active area of the menu item.</td>
 * </tr>
 * <tr>
 * <td>MenuDragOut</td>
 * <td>occurs when the mouse button is clicked and the mouse cursor is dragged
 * out of the active area of the menu item.</td>
 * </tr>
 * <tr>
 * <td>ReleaseOut</td>
 * <td>occurs when the mouse button is clicked and the mouse cursor is dragged
 * into the active area of the menu item.</td>
 * </tr>
 * </table>
 * 
 * <p>
 * In addition to responding to mouse events, buttons also respond to keys being
 * pressed on the keyboard. Keyboard events are defined by the character key
 * being pressed, e.g. "t", "T", "$", etc. For control keys a number of reserved
 * names are supported:
 * </p>
 * 
 * <table class="datasheet">
 * <tr>
 * <td>&lt;Left&gt;</td>
 * <td>Left arrow key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Right&gt;</td>
 * <td>Right arrow key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Home&gt;</td>
 * <td>Home key.</td>
 * </tr>
 * <tr>
 * <td>&lt;End&gt;</td>
 * <td>End key</td>
 * </tr>
 * <tr>
 * <td>&lt;Insert&gt;</td>
 * <td>Insert key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Delete&gt;</td>
 * <td>Delete key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Backspace&gt;</td>
 * <td>Backspace key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Enter&gt;</td>
 * <td>Enter (return) key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Up&gt;</td>
 * <td>Up arrow key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Down&gt;</td>
 * <td>Down arrow key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Pageup&gt;</td>
 * <td>Page up key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Pagedown&gt;</td>
 * <td>Page down key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Tab&gt;</td>
 * <td>Tab key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Escape&gt;</td>
 * <td>Escape key.</td>
 * </tr>
 * <tr>
 * <td>&lt;Space&gt;</td>
 * <td>Space bar.</td>
 * </tr>
 * </table>
 * 
 * <p>
 * Since the event code allows multiple events, the code for compound events can
 * be created by performing a bit-wise Or of the individual codes:
 * </p>
 * 
 * <pre>
 *  int eventCode = FSButtonEvent.RollOver | FSButtonEvent.Press;&quot;;
 * </pre>
 * 
 * <p>
 * The class method <b>codeForKey</b> returns the event code that identifies
 * when a specific key is pressed:
 * </p>
 * 
 * <pre>
 * int eventCode = FSButtonEvent.codeForKey('J');
 * </pre>
 * 
 * <p>
 * Control keys are identified using one of the reserved ButtonEvent values:
 * </p>
 * 
 * <pre>
 * int eventCode = FSButtonEvent.Enter | FSButtonEvent.PageUp;
 * </pre>
 * 
 * <p>
 * However while multiple mouse events can be defined for a button only one
 * keyboard event can be defined.
 * </p>
 * 
 * <table class="datasheet">
 * 
 * <tr>
 * <th align="left" colspan="2">Attributes</th>
 * </tr>
 * 
 * <tr>
 * <td>event</td>
 * <td>a code identifying the different types of button events that the actions
 * defined in this object will be executed in response to.</td>
 * </tr>
 * 
 * <tr>
 * <td>actions</td>
 * <td>An array of action objects that are executed when the events defined in
 * the event code occur.</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>
 * </table>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSButtonEvent class represents the ButtonCondAction data structure from
 * the Macromedia Flash (SWF) File Format Specification. It was introduced in
 * Flash 3.
 * </p>
 */
public class FSButtonEvent extends FSTransformObject
{
	/**
	 * Defines the button event that occurs when the mouse cursor moves over the
	 * active area of a button.
	 */
	public static final int RollOver = 1;

	/**
	 * Defines the button event that occurs when the mouse cursor moves out of
	 * the active area of a button.
	 */
	public static final int RollOut = 2;

	/**
	 * Defines the button event that occurs when the mouse button is clicked
	 * while the mouse cursor is over the active area of the button.
	 */
	public static final int Press = 4;

	/**
	 * Defines the button event that occurs when the mouse button is clicked and
	 * released while the mouse cursor is over the active area of the button.
	 */
	public static final int Release = 8;

	/**
	 * Defines the button event that occurs when the mouse button is clicked and
	 * the mouse cursor is dragged out of the active area of the button.
	 */
	public static final int DragOut = 16;

	/**
	 * Defines the button event that occurs when the mouse button is clicked and
	 * the mouse cursor is dragged into the active area of the button.
	 */
	public static final int DragOver = 32;

	/**
	 * Defines the button event that occurs when the mouse button is clicked,
	 * the mouse cursor is dragged into the active area of the button and the
	 * mouse button is released.
	 */
	public static final int ReleaseOut = 64;

	/**
	 * Defines the button event that occurs when the mouse button is clicked and
	 * the mouse cursor is dragged into the active area of the menu item.
	 */
	public static final int MenuDragOver = 128;

	/**
	 * Defines the button event that occurs when the mouse button is clicked and
	 * the mouse cursor is dragged out of the active area of the menu item.
	 */
	public static final int MenuDragOut = 256;

	/**
	 * Defines the button event that occurs when the left arrow key is pressed
	 * on the keyboard.
	 */
	public static final int Left = 512;

	/**
	 * Defines the button event that occurs when the right arrow key is pressed
	 * on the keyboard.
	 */
	public static final int Right = 1024;

	/**
	 * Defines the button event that occurs when the home key is pressed on the
	 * keyboard.
	 */
	public static final int Home = 1536;

	/**
	 * Defines the button event that occurs when the end key is pressed on the
	 * keyboard.
	 */
	public static final int End = 2048;

	/**
	 * Defines the button event that occurs when the insert key is pressed on
	 * the keyboard.
	 */
	public static final int Insert = 2560;

	/**
	 * Defines the button event that occurs when the delete key is pressed on
	 * the keyboard.
	 */
	public static final int Delete = 3072;

	/**
	 * Defines the button event that occurs when the backspace key is pressed on
	 * the keyboard.
	 */
	public static final int Backspace = 4096;

	/**
	 * Defines the button event that occurs when the enter key is pressed on the
	 * keyboard.
	 */
	public static final int Enter = 6656;

	/**
	 * Defines the button event that occurs when the up arrow key is pressed on
	 * the keyboard.
	 */
	public static final int Up = 7168;

	/**
	 * Defines the button event that occurs when the down arrow key is pressed
	 * on the keyboard.
	 */
	public static final int Down = 7680;

	/**
	 * Defines the button event that occurs when the page up key is pressed on
	 * the keyboard.
	 */
	public static final int Pageup = 8192;

	/**
	 * Defines the button event that occurs when the page down key is pressed on
	 * the keyboard.
	 */
	public static final int Pagedown = 8704;

	/**
	 * Defines the button event that occurs when the tab key is pressed on the
	 * keyboard.
	 */
	public static final int Tab = 9216;

	/**
	 * Defines the button event that occurs when the escape key is pressed on
	 * the keyboard.
	 */
	public static final int Escape = 9728;

	/**
	 * Defines the button event that occurs when the space bar is pressed on the
	 * keyboard.
	 */
	public static final int Space = 16384;

	/**
	 * Generates the code identifying a particular event using the name of the
	 * event.
	 * 
	 * @param c
	 *            a keyboard character.
	 * @return the event code corresponding to the specified event.
	 */
	public static int codeForKey(char c)
	{
		return c << 9;
	}

	private int event = 0;
	private byte[] encodedActions = null;

	private int length = 0;
	private ArrayList actions = null;

	/**
	 * Construct an FSButtonEvent object, initialising it with values decoded
	 * from an encoded object.
	 * 
	 * @param coder
	 *            an FSCoder containing the binary data.
	 */
	public FSButtonEvent(FSCoder coder, int len)
	{
		length = len - 2;
		decode(coder);
	}

	/**
	 * Constructs an FSButtonEvent object that defines the array of actions that
	 * will be executed when a particular event occurs.
	 * 
	 * @param aNumber
	 *            the event code.
	 * @param anArray
	 *            the array of action objects that will be executed when the
	 *            specified event(s) occur.
	 */
	public FSButtonEvent(int aNumber, ArrayList anArray)
	{
		setEvent(aNumber);
		setActions(anArray);
	}

	/**
	 * Constructs an FSButtonEvent object that defines the array of actions that
	 * will be executed when a particular event occurs.
	 * 
	 * @param aNumber
	 *            the event code.
	 * @param bytes
	 *            an array of encoded action objects.
	 */
	public FSButtonEvent(int aNumber, byte[] bytes)
	{
		setEvent(aNumber);
		setEncodedActions(bytes);
	}

	/**
	 * Constructs an FSButtonEvent object by copying values from an existing
	 * object.
	 * 
	 * @param obj
	 *            an FSButtonEvent object.
	 */
	public FSButtonEvent(FSButtonEvent obj)
	{
		event = obj.event;

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

	/**
	 * Add an action to the end of the actions array.
	 * 
	 * @param anAction
	 *            an object derived from the base class FSActionObject.
	 */
	public void add(FSActionObject anAction)
	{
		if (encodedActions != null)
		{
			actions = FSMovie.decodeActions(encodedActions);
			encodedActions = null;
		}
		actions.add(anAction);
	}

	/**
	 * Gets the event code that this FSButtonEvent defines actions for.
	 * 
	 * @return the compound event code.
	 */
	public int getEvent()
	{
		return event;
	}

	/**
	 * Gets the array of actions that are executed by the button in response to
	 * specified event(s).
	 * 
	 * @return the array of action objects that will be executed when the
	 *         specified event(s) occur.
	 */
	public ArrayList getActions()
	{
		if (encodedActions != null)
		{
			actions = FSMovie.decodeActions(encodedActions);
			encodedActions = null;
		}
		return actions;
	}

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

	/**
	 * Sets the event code that this FSButtonEvent defines actions for.
	 * 
	 * @param aNumber
	 *            the event code.
	 */
	public void setEvent(int aNumber)
	{
		event = aNumber;
	}

	/**
	 * Sets the array of actions that are executed by the button in response to
	 * specified event(s).
	 * 
	 * @param anArray
	 *            the array of action objects that will be executed when the
	 *            specified event(s) occur.
	 */
	public void setActions(ArrayList anArray)
	{
		actions = anArray;
		encodedActions = null;
	}

	/**
	 * 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()
	{
		FSButtonEvent anObject = (FSButtonEvent) 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;
	}

	/**
	 * Returns true if anObject is equal to this one. Objects are considered
	 * equal if they would generate identical binary data when they are encoded
	 * to a Flash file.
	 * 
	 * @return true if this object would be identical to anObject when encoded.
	 */
	public boolean equals(Object anObject)
	{
		boolean result = false;

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

			result = event == typedObject.event;

			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, "event", event);

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

			buffer.append("}");
		}
	}

	public int length(FSCoder 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)
	{
		coder.writeWord(event, 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);
			}
		}
	}

	public void decode(FSCoder coder)
	{
		event = coder.readWord(2, false);

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

			int start;

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

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