using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class GameStateController : MonoBehaviour
{
    #region Singleton
    private static GameStateController _instance;

    // Public reference to the singleton instance
    public static GameStateController Instance
    {
        get
        {
            // If the instance doesn't exist, try to find it in the scene
            if (_instance == null)
            {
                _instance = FindObjectOfType<GameStateController>();

                // If it's still null, create a new GameObject and add the component
                if (_instance == null)
                {
                    GameObject singletonObject = new GameObject(typeof(GameStateController).Name);
                    _instance = singletonObject.AddComponent<GameStateController>();
                }
            }
            return _instance;
        }
    }
    #endregion

    private GameState currentState;
    public GameState CurrentState
    {
        get
        {
            return currentState;
        }
        private set
        {
            if (value != currentState)
            {
                currentState = value;
                if (onCurrentGameStateChanged != null)
                    onCurrentGameStateChanged.Raise((int)currentState);
            }
        }
    }

    [Header("Events:")]
    [SerializeField] private GameEvent_Int onCurrentGameStateChanged;

    [Header("Listeners:")]
    [SerializeField] private GameEventListener onLoadLevelStarting;
    [SerializeField] private GameEventListener_ZoneData onGameSceneLoaded;



    private void Awake()
    {
        DontDestroyOnLoad(this);

        onLoadLevelStarting.Response.AddListener(HandleLoadLevelStartingEvent);
        onGameSceneLoaded.Response.AddListener(HandleGameSceneLoadedEvent);
    }

    // Start is called before the first frame update
    void Start()
    {
        CurrentState = GameState.Intro;
        onCurrentGameStateChanged.Raise((int)currentState);
    }

    private void HandleLoadLevelStartingEvent()
    {
        CurrentState = GameState.Loading;
    }
    private void HandleGameSceneLoadedEvent(ZoneData zoneData)
    {
        if (PhotonNetwork.InRoom)
            CurrentState = GameState.GameScene;
        else
            StartCoroutine(WaitForRoomConnection());
    }

    IEnumerator WaitForRoomConnection()
    {
        yield return new WaitUntil(() => PhotonNetwork.InRoom);

        CurrentState = GameState.GameScene;
    }
}

public enum GameState
{
    Intro,
    Menu,
    Loading,
    GameScene
}