/**
 *
 */
package de.rico.adventure.actions.custom;

import javax.media.opengl.GL;

import de.rico.adventure.actions.AbstractAction;
import de.rico.adventure.actions.ActionScheduler;
import de.rico.adventure.entity.character.PlayableCharacter;
import de.rico.adventure.entity.item.Item;
import de.rico.engine.geometry.MeshVA;
import de.rico.engine.geometry.modelloader.Animation;

/**
 * This game action can be used to let a playable character
 * pick up an item from the room he is currently located in.
 * @author Frank Bruns
 */
public class PickUp extends AbstractAction
{
	private Item item = null;

	private String animName = null;
	private Animation backupAnim = null;

	/**
	 * Creates a new item pick up action.
	 * @param player player character that picks up the item
	 * @param item item to pick up
	 */
	public PickUp(PlayableCharacter player, Item item)
	{
		super(player);
		this.item = item;
	}

	/**
	 * Creates a new item pick up action with the specified animation
	 * attached to it.
	 * @param player player character that picks up the item
	 * @param item item to pick up
	 * @param animName name of the animation to play while the
	 * action is active
	 */
	public PickUp(PlayableCharacter player, Item item, String animName)
	{
		this(player, item);
		this.animName = animName;
	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#update(long)
	 */
	@Override
	public void update(long elapsedTime)
	{
		PlayableCharacter player = (PlayableCharacter)this.getEntity();
		MeshVA model = (MeshVA)player.getMesh();

		// backup the current animation, if animated mesh
		if(this.backupAnim == null
				&& player.getMesh() instanceof MeshVA)
		{
			this.backupAnim = model.getCurrentAnimation();

			// set new animation
			model.setAnimation(this.animName);
			model.getCurrentAnimation().start();
		}


		// let the playable character pick up the item
		if(player.getInventory().contains(this.item) == false)
			player.pickUp(this.item);

		// remove the pick action from the scheduler
		// after the animation frames have been played
		if(this.animName != null
				&& model.getCurrentAnimation().getCurrentFrame()
					== model.getCurrentAnimation().getEndFrame())
			ActionScheduler.getInstance().removeFirst();
	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#draw(javax.media.opengl.GL)
	 */
	@Override
	public void draw(GL gl)
	{
		// do nothing
	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#forceFinish()
	 */
	@Override
	public void finishUp()
	{
		// reset to original animation
		if(this.backupAnim != null
				&& this.getEntity().getMesh() instanceof MeshVA)
		{
			MeshVA model = (MeshVA)this.getEntity().getMesh();

			// stop and reset animation to initial status
			model.getCurrentAnimation().stop();
			model.getCurrentAnimation().reset();

			// set old animation
			model.setAnimation(this.backupAnim.getName());
			model.getCurrentAnimation().start();
		}
	}

}
