package ei.engine.effects;

import java.awt.Rectangle;

import org.lwjgl.opengl.GL11;

import ei.engine.scene.Entity;
import ei.engine.texture.Texture;

/**
 * Fades out/in Things
 * @author Ziver
 *
 */
public class Fade extends Entity{
	// The entity to fade
	private Entity entity;
	
	//Temp variables
	private float life;
	private boolean fadeOut;
	private float fade;

	public Fade(String name) {
		super(name);
		life = 1.0f;
		fadeOut = true;
		fade = 0.01f;
	}

	/**
	 * Draws out the fade and the entity
	 */
	public void render(){
		// store the current model matrix
		GL11.glPushMatrix();
		GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
		
		entity.getTexture().getColor().setA(life);
		entity.render();
		
		GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
		// restore the model view matrix to prevent contamination
		GL11.glPopMatrix();
	}
	
	/**
	 * Updates the fade and the entity
	 */
	public void update(){
		if(fadeOut){
			if(life > 0)
				life -= fade;
		}
		else{
			if(life < 1)
				life += fade;
		}
		entity.update();
	}
	
	public void setEntity(Entity e){
		entity = e;
	}
	
	/**
	 * Returns true if the fade is done else false
	 * @return True if the fade is done else false
	 */
	public boolean isDone(){
		if(life <= 0){
			return  true;
		}
		else if(life >= 1){
			return true;
		}
		return false;
	}
	
	/**
	 * Set the time of the fade
	 * 
	 * @param f The time of the fade
	 */
	public void setFade(float f){
		fade = f;
	}
	
	/**
	 * Set if the object should fade out or in
	 * 
	 * @param b True for fade out false for fade in
	 */
	public void fadeOut(boolean b){
		fadeOut = b;
		if(fadeOut)life = 1.0f;
		else life = 0.0f;
	}
	
	/**
	 * Get the bounds of the entity
	 */
	public Rectangle getBound() {
		return entity.getBound();
	}

	@Override
	public Texture getTexture() {
		return entity.getTexture();
	}
	
}
