using UnityEngine;
using System.Collections;

public enum FADE {
	IN,
	OUT,
	NONE
}
public enum FADETYPE {
	LINEAR,
	QUADRATIC
}
public class AlphaFade : MonoBehaviour {
	
	private FADE state = FADE.NONE;
	private float fadeTime = 2f;
	private float timer = 0f;
	private float startAlpha = 0f;
	private float maxAlpha = 1f;
	private FADETYPE fadeType = FADETYPE.LINEAR;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if(state!=FADE.NONE){ 
			Color temp = renderer.material.color;
			timer+=Time.deltaTime/fadeTime;
			if(state==FADE.IN) {
				temp.a=1-Mathf.Pow(1-timer,(int)fadeType+1);
			} else {
				temp.a=1-Mathf.Pow(timer,(int)fadeType+1);
			}
			if(timer>=1) {
				state = FADE.NONE;
				timer=0;
			} else {
				temp.a*=maxAlpha;
				renderer.material.color = temp;	
			}
		}
	}
	
	void Fade (FADE f,float time) {
		if(maxAlpha!=0f) {
			startAlpha = renderer.material.color.a/maxAlpha;
		} else {
			startAlpha = renderer.material.color.a;
		}
		fadeTime = time;
		state = f;
			
		switch(f){
		case(FADE.IN):
			if(fadeType==FADETYPE.LINEAR){
				timer = startAlpha;
			} else {
				timer = 1-Mathf.Sqrt (1-startAlpha)	;
			}
			break;
		case(FADE.OUT):
			if(fadeType==FADETYPE.LINEAR){
				timer = 1-startAlpha;
			} else {
				timer = Mathf.Sqrt(1-startAlpha);
			}
			break;
		}
				
	}
	
	public void FadeIn (float time) {
		startAlpha = renderer.material.color.a;	
		fadeTime = time;
		state = FADE.IN;
		if(fadeType==FADETYPE.LINEAR){
			timer = startAlpha;
		} else {
			timer = 1-Mathf.Sqrt (1-startAlpha)	;
		}		
	}
	
	public void FadeOut (float time) {
		startAlpha = renderer.material.color.a;	
		fadeTime = time;
		state = FADE.OUT;
		if(fadeType==FADETYPE.LINEAR){
			timer = 1-startAlpha;
		} else {
			timer = Mathf.Sqrt(1-startAlpha);
		}				
	}
	
	public void SetFadetype(FADETYPE t){
		fadeType=t;	
	}
	
	public void SetMaxAlpha(float mxA){
		maxAlpha = Mathf.Clamp (mxA,0.001f,1f);	
	}
	public void SetAlpha (float a){
		Color temp =  renderer.material.color;
		temp.a = a;
		renderer.material.color = temp;
	}
}
