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;

/**
 * This class can be used to set the animation of an entity. The animation will
 * be played continously until another animation is set to the entity.
 * @author Frank Bruns
 */
public class SetAnimation extends AbstractAction
{

	private State backupState = null;

	private String animName = null;

	private boolean loop = false;

	/**
	 * Creates a new game action to set an entity's animation.
	 * @param e entity to set the animation of
	 * @param animName name of the animation to set
	 * @param loop loop the animation? --> true=yes, false=no
	 */
	public SetAnimation(AbstractEntity e, String animName, boolean loop)
	{
		super(e);
		this.animName = animName;
		this.loop = loop;
	}

	/*
	 * (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()
	{
		MeshVA model = (MeshVA) this.getEntity().getMesh();

		// stop animation, if not set to loop!
		// the last frame will be kept active
		if (this.loop == false) model.getCurrentAnimation().stop();

		// 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 and start new animation
		if (this.backupState == null)
		{
			this.backupState = StateManager.getInstance().getState();

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

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

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

	}

}
