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.AbstractEntity;
import de.rico.adventure.enums.State;
import de.rico.adventure.structure.StateManager;
import de.rico.engine.geometry.MeshVA;
import de.rico.engine.geometry.modelloader.Animation;

/**
 * This class can be used to play an animation of an entity.
 * @author Frank Bruns
 *
 */
public class PlayAnimation extends AbstractAction
{

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

	private State backupState = null;

	/**
	 * Creates a new game action to play an entity's animation.
	 * @param e entity to play the animation of
	 * @param animName name of the animation to play
	 */
	public PlayAnimation(AbstractEntity e, String animName)
	{
		super(e);
		this.animName = animName;
	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#draw(javax.media.opengl.GL)
	 */
	@Override
	public void draw(GL gl)
	{
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#finishUp()
	 */
	@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();
		}

		// restore old state
		StateManager.getInstance().setState(this.backupState);
	}

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

		// save original game state
		if(this.backupState == null)
			this.backupState = StateManager.getInstance().getState();

		if(this.backupState != State.NO_INPUT_CINEMATIC)
			StateManager.getInstance().setState(State.NO_INPUT);

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

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


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

	}

}
