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

public class StateController : MonoBehaviour {

    [Header("Respawning")]
    [SerializeField] GameObject player;
    public GameObject spawnPoint;
    [SerializeField] private GameObject deathCanvas;

    [Header("Pause Menu")]
    public bool isPaused = false;
    public GameObject pauseMenuCanvas;

    [Header("Debug")]
    public bool inDebugMode;
    GameObject debugCanvas;

    void Awake() {
        // check to see if a state controller already exists
        if (GameObject.FindGameObjectWithTag("StateController") != null) {
            Destroy(this.gameObject);
        } else { // if it doesn't, then this is the only one
            this.gameObject.tag = "StateController";
        }
        DontDestroyOnLoad(this.gameObject);
        SceneManager.sceneLoaded += OnSceneLoaded;

        if (inDebugMode) {
            debugCanvas = GameObject.Find("DebugCanvas");
            debugCanvas.SetActive(false);
        }
    }

    void OnSceneLoaded(Scene scene, LoadSceneMode mode) { 
        deathCanvas = GameObject.Find("DeathUICanvas");
        if (deathCanvas != null) {
            Button respawnButton = GameObject.Find("RespawnButton").GetComponent<Button>();
            respawnButton.onClick.AddListener(RespawnPlayer);
            deathCanvas.SetActive(false);
        }

        pauseMenuCanvas = GameObject.Find("PauseMenuCanvas");
        if (pauseMenuCanvas != null) {
            Button resumeButton = GameObject.Find("ResumeButton").GetComponent<Button>();
            resumeButton.onClick.AddListener(Unpause);
            TogglePauseMenu(false);
        }

        if (isPaused) {
            Unpause();
        }
    }

    void OnToggleDebugMenu() {
        if (inDebugMode) {
            debugCanvas.SetActive(!debugCanvas.activeSelf);
        }
    }

    void OnPause() {
        if (pauseMenuCanvas != null) {
            if (!isPaused) {
                Time.timeScale = 0;
                TogglePauseMenu(true);
            } else {
                Time.timeScale = 1;
                TogglePauseMenu(false);
            }
            isPaused = !isPaused;
        }
    }

    public void Unpause() {
        Time.timeScale = 1;
        TogglePauseMenu(false);
        isPaused = !isPaused;
    }

    void TogglePauseMenu(bool showPauseMenu) {
        pauseMenuCanvas.SetActive(showPauseMenu);
    }

    public void RespawnPlayer() {
        SetDeathCanvasActive(false);
        GameObject.Find("Main Camera").GetComponent<CameraMovement>().FindPlayer();
        Instantiate(player, spawnPoint.transform.position, player.transform.rotation);
    }

    public void SetDeathCanvasActive(bool activeState) {
        deathCanvas.SetActive(activeState);
    }
}
