using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class StageManagerScript : MonoBehaviour {

	public int absorbPlanetNum;
	public int expelPlanetNum;

	[HideInInspector]
	public int absorbPlanetCount;
	[HideInInspector]
	public int expelPlanetCount;

	public Text absorbPlanetCountLabel;
	public Text expelPlanetCountLabel;

	public enum GameState { WAIT, LAUNCHED, DESTRUCTION, FAILED };
	public GameState currentState;

	public static StageManagerScript instance;

	// Use this for initialization
	void Start () {
		absorbPlanetCount = absorbPlanetNum;
		expelPlanetCount = expelPlanetNum;

		UpdateLabels ();

		instance = this;
	}

	public void UpdateLabels()
	{
		absorbPlanetCountLabel.text = absorbPlanetCount.ToString ();
		expelPlanetCountLabel.text = expelPlanetCount.ToString ();
	}

	public void StartReloadingThisStage(){
		currentState = GameState.FAILED;

		StartCoroutine (ReloadScene ());
	}

	public void StartLoadingNextStage(){
		currentState = GameState.DESTRUCTION;

		StartCoroutine (LoadNextScene ());
	}

	IEnumerator LoadNextScene(){
		yield return new WaitForSeconds (5f);
		AudioManagerScript.instance.saveCurrentTimeSong ();
		Debug.Log ((SceneManager.GetActiveScene ().buildIndex + 1) % SceneManager.sceneCount);
		SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex+1);
	}

	IEnumerator ReloadScene(){
		yield return new WaitForSeconds (2f);
		AudioManagerScript.instance.saveCurrentTimeSong ();
		SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex);
	}

	public void Reload()
	{
		AudioManagerScript.instance.saveCurrentTimeSong ();
		SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex);
	}
	
	// Update is called once per frame
	void Update () {
		switch (currentState) {
		case GameState.WAIT:
			{
				if (PlayerScript.player)
					if (!PlayerScript.player.isStable)
						currentState = GameState.LAUNCHED;
			}
			break;
		}
	}
}
