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

public class SceneController : MonoBehaviour
{

    public static SceneController Instance = null;

    // this object will always exist!
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        // Make this object stay around when switching scenes
        DontDestroyOnLoad(this.gameObject);
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        GameObject pauseMenu = GameObject.Find("PauseMenuCanvas");
        if (pauseMenu != null)
        {
            Button quitButton = GameObject.Find("QuitButton").GetComponent<Button>();
            quitButton.onClick.AddListener(BackToMainMenu);
        }
        if (scene.buildIndex == 0)
        { // if this is the menu
            GameObject.Find("NewGameButton").GetComponent<Button>().onClick.AddListener(NextScene);
        }

        // if this is the last scene
        if (scene.buildIndex == (SceneManager.sceneCountInBuildSettings - 1)) {
            GameObject backToMenuButton = GameObject.Find("BackToMenuButton");
            if (backToMenuButton != null) {
                backToMenuButton.GetComponent<Button>().onClick.AddListener(delegate{LoadChosenScene(0);});
                backToMenuButton.SetActive(false);
            }
        }
    }

    public void NextScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }

    public void BackToMainMenu()
    {
        SceneManager.LoadScene(0); // main menu scene should be 0
    }

    public void LoadChosenScene(int index)
    {
        SceneManager.LoadScene(index);
    }

    public void LoadSceneByName(string name) {
        SceneManager.LoadScene(name);
    }

}
