using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.SceneManagement;

public class GameMaster : MonoBehaviour
{
    #region Instance
	private static GameMaster _instance;
	public static GameMaster Instance
	{
		get
		{
			if (_instance == null)
				_instance = FindObjectOfType<GameMaster>();
			return _instance;
		}
	}
    #endregion

    public enum GameState { splash, neighborhood, battle }
    public GameState currentState = GameState.neighborhood;

    private Gesture.GestureName[] gestures;

    private static GameObject _neighborCamera;

    public static GameObject NeighborCamera
	{
        get
		{
			if (_neighborCamera == null)
				_neighborCamera = GameObject.Find ("Main Camera");
			return _neighborCamera;
        }
    }

	private void Awake()
	{
        if (Instance != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            DontDestroyOnLoad(this.gameObject);
            DOTween.Init();
			currentState = GameState.neighborhood;
        }
	}

    public void OpenBattle(Gesture.GestureName[] gestureNames)
    {
        gestures = gestureNames;
        StartCoroutine(LoadBattle());
    }

    private IEnumerator LoadBattle()
    {
        AudioMaster.StartBattleSong();

        SceneManager.LoadScene("Battle Scene", LoadSceneMode.Additive);

        yield return new WaitForEndOfFrame();

        NeighborCamera.SetActive(false);
        currentState = GameState.battle;
    }

    public void CloseBattle(bool victory)
    {
        StartCoroutine(UnloadBattle(victory));
    }

    private IEnumerator UnloadBattle(bool victory)
    {
        AsyncOperation asyncOp = SceneManager.UnloadSceneAsync("Battle Scene");

        while (!asyncOp.isDone)
            yield return 0;

        NeighborhoodMaster.Instance.BackFromBattle(victory);
        NeighborCamera.SetActive(true);
        currentState = GameState.neighborhood;

        AudioMaster.StartMainSong();
    }

    public Gesture.GestureName[] GetGestureNames()
    {
        return gestures;
    }
}
