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;

/**
 * This game action fades an entity to a certain transparency level
 * @author Frank Bruns
 *
 */
public class FadeEntityToTransparent extends AbstractAction
{
	private int fadeDuration = 0;
	private long cumulatedTime = 0L;
	private float startAlpha = 0f;
	private float alpha = 0f; // alpha value to reach
	private State backupState = null;

	/**
	 * Creates a game action that fades an entity to a certain transparency level
	 * @param entity entity to fade
	 * @param goalAlpha alpha value to target
	 * @param dur time to use for the fading process
	 */
	public FadeEntityToTransparent(AbstractEntity entity, float goalAlpha, int dur)
	{
		super(entity);
		this.fadeDuration = dur;
		this.alpha = goalAlpha;
		this.startAlpha = entity.getMesh().getMaterial().getDiffuse().alpha;
	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#update(long)
	 */
	@Override
	public void update(long elapsedTime)
	{
		// save original game state
		if(this.backupState == null)
			this.backupState = StateManager.getInstance().getState();

		//StateManager.getInstance().setState(State.NO_INPUT);

		this.cumulatedTime += elapsedTime;

		float factor = (float)this.cumulatedTime/(float)this.fadeDuration;

		float newAlpha = this.startAlpha + factor*(this.alpha-this.startAlpha);

		this.getEntity().getMesh().setTransparency(newAlpha);

		// remove action as soon as the time for fading has expired
		if(this.cumulatedTime >= this.fadeDuration)
		{
			ActionScheduler.getInstance().removeFirst();

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

	/* (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()
	{
		// set the desired alpha value in any case
		this.getEntity().getMesh().setTransparency(this.alpha);

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