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.enums.State;
import de.rico.adventure.structure.StateManager;
import de.rico.engine.camera.Camera;
import de.rico.engine.effect.ortho.RectangleRenderer;
import de.rico.engine.material.Color4f;

/**
 * This game action fades the screen in from a certain color.
 * @author Frank Bruns
 *
 */
public class FadeIn extends AbstractAction
{
	private int fadeDuration = 0;
	private long cumulatedTime = 0L;
	private State backupState = null;

	private RectangleRenderer rectRenderer = null;

	/**
	 * Creates a game action that fades the screen in from a certain color.
	 * The color to fade from can be kept up for a certain amount of time
	 * before the fading actually starts.
	 * @param red amount of red to fade in from
	 * @param green amount of green to fade in from
	 * @param blue amount of blue to fade in from
	 * @param fadingTime time to use for the fading process
	 */
	public FadeIn(float red, float green, float blue, int fadingTime)
	{
		this.fadeDuration = fadingTime;
		this.rectRenderer = new RectangleRenderer(new Color4f(red,green,blue,1f));
	}

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

		// set the new alpha value of the rectangle renderer
		this.rectRenderer.getColor().setAlpha(1f-((float)this.cumulatedTime/(float)this.fadeDuration));

		// 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)
	{
		this.rectRenderer.drawRectangle(
				0, 0,
				Camera.getInstance().getViewPort().getWidth(),
				Camera.getInstance().getViewPort().getHeight());
	}

	/* (non-Javadoc)
	 * @see de.rico.adventure.actions.AbstractAction#finishUp()
	 */
	@Override
	public void finishUp()
	{
		// restore old state
		StateManager.getInstance().setState(this.backupState);
	}
}
