using UnityEngine;
using System.Collections;

public class SplashScreen : MonoBehaviour {

	public GUISkin skin;

	public GUITexture tex;

	float fadeStart;
	float fadeTime = 5f;
	float fadeFrac = 1;

	float myWidth = 110f;
	float myHeight = 50f;

	public int currentLevel = 0;
	public int maxLevel = 2;

	bool fadeOut = false;
	bool fadeIn = false;

	float otherFadeFrac = 0.5f;

	void Start(){
		SplashScreen[] splashes = GameObject.FindObjectsOfType<SplashScreen>();
		if(splashes.Length > 1){
			for(int i = 1; i < splashes.Length; i++)
			{
				GameObject.Destroy(splashes[i].gameObject);
			}
		}

		GameObject.DontDestroyOnLoad(this);
		GameObject.DontDestroyOnLoad(tex);
		fadeStart = Time.time;
	}

	bool restartingLevel = false;

	void Update(){

		if(Input.GetKeyDown(KeyCode.X))
		{
			Debug.Log("Restarting level " + currentLevel);

			StartCoroutine(RestartLevel());
		}

		if(restartingLevel){
			tex.color = new Color(tex.color.r,tex.color.g,tex.color.b,otherFadeFrac);
		}

		if(currentLevel == 0)
		{
			fadeFrac = 1-(Time.time-fadeStart)/fadeTime;
			if(fadeFrac <= 0f){
				currentLevel++;
				restartingLevel = true;
				Application.LoadLevel("Level" + currentLevel);
			}
		}
	}

	void OnLevelWasLoaded(){
		if(currentLevel > 0)
		{
			StartCoroutine(AfterLevelLoad());
		}
	}

	void OnGUI(){
		GUI.Box(new Rect(0f,0f,Screen.width,Screen.height),"",skin.box);
		skin.label.normal.textColor = new Color(skin.label.normal.textColor.r,skin.label.normal.textColor.g,skin.label.normal.textColor.b,fadeFrac);
		GUI.Label(new Rect(Screen.width/2-myWidth/2,Screen.height/2-myHeight/2,myWidth,myHeight),"Permanence",	skin.label);
	}

	float otherFadeStart;
	float otherFadeTime = 0.5f;

	public void Reload(){
		Debug.Log("Relading Level");
		StartCoroutine(RestartLevel());
	}

	public IEnumerator RestartLevel(){
		restartingLevel = true;
		otherFadeStart = Time.time;
		while(otherFadeFrac < 1)
		{
			otherFadeFrac = (Time.time-otherFadeStart)/otherFadeTime;
			yield return null;
		}

		Application.LoadLevel("Level" + currentLevel);
	}

	public IEnumerator AfterLevelLoad(){
		otherFadeStart = Time.time;
		while(otherFadeFrac > 0)
		{
			otherFadeFrac = 1-(Time.time-otherFadeStart)/otherFadeTime;
			yield return null;
		}
		restartingLevel = false;
	}

	public void GoToNextLevel(){
		Debug.Log("Go to next level");
		currentLevel++;
		if(maxLevel < currentLevel)
		{
			Debug.Log("Game complete, loading menu");
			currentLevel = 0;
			RestartLevel();
		} else {
			Debug.Log("Game complete, going to next level");
			StartCoroutine(RestartLevel());
		}
	}
}
