using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public delegate void OnStateChangeHandler();

public class StateManager : BaseManager {
    public event OnStateChangeHandler OnStateChange;

    // --------------- Singleton Pattern ---------------
    private static StateManager instance = null;

    public static StateManager Instance { 
        get {
            if (instance == null) {
                instance = Object.FindObjectOfType(typeof(StateManager)) as StateManager;

                if (instance == null) {
                    GameObject go = new GameObject("Manager");
                    DontDestroyOnLoad(go);
                    instance = go.AddComponent<StateManager>();
                }
                DontDestroyOnLoad(instance.gameObject);
            }
            return instance;
        }
    }
    // --------------- Singleton Pattern ---------------

    [HideInInspector, SerializeField]
    public string selectedScene;

    public SceneState currentGameState;
    public GuiState currentGuiState;

    public GameObject guiCamera;

    static public bool IsActive() {
        return instance != null;
    }

    private void Update() {
        if (Input.GetKeyDown(KeyCode.Escape)) {
            Application.Quit();
        }
    }

    public void SetGameState(SceneState newGameState) {
        if (newGameState == null) {
            return;
        }

        if (currentGameState != null) {
            currentGameState.Disable();
        }

        this.currentGameState = newGameState;

        Application.LoadLevel(currentGameState.selectedScene);

        StartCoroutine(WaitForLevelToLoad());
    }

    private IEnumerator WaitForLevelToLoad() {
        while (Application.isLoadingLevel)
            yield return 1;

        currentGameState.Enable();

        if (OnStateChange != null) {
            OnStateChange();
        }
    }
}
