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

public class GameManager : MonoBehaviour
{
    public PanelGroup panelGroup;
    public AudioSource audioSource;
    public GamePanel gamePanel => panelGroup.GetPanel<GamePanel>();
    public PausePanel pausePanel => panelGroup.GetPanel<PausePanel>();
    public FinishPanel finishPanel => panelGroup.GetPanel<FinishPanel>();

    public Level level;

    private bool finished;

    public static GameManager instance { get; private set; }


    private void Awake()
    {
        instance = this;
        Application.targetFrameRate = 60;
    }

    private void Start()
    {
        gamePanel.OpenPanel();
        SetCursor(false);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (Time.timeScale == 1)
                Pause();
            else
                Resume();
        }
    }

    public void PlayAudioEffect(AudioClip clip)
    {
        audioSource.PlayOneShot(clip);
    }

    public static void LoadLevel(int levelIndex)
    {
        SetPause(false);
        SceneManager.LoadScene("Game");
        SceneManager.LoadScene(levelIndex, LoadSceneMode.Additive);
    }

    public static void LoadNextLevel()
    {
        var currentScene = SceneManager.GetActiveScene().buildIndex;
        var nextScene = currentScene + 1 >= SceneManager.sceneCountInBuildSettings ? -1 : currentScene + 1;
        if (nextScene == -1)
        {
            MenuManager.LoadMenu();
        }
        else
        {
            LoadLevel(nextScene);
        }
    }

    public static void SetPause(bool pause)
    {
        Time.timeScale = pause ? 0 : 1;
    }

    public static void SetCursor(bool visible)
    {
        Cursor.lockState = visible ? CursorLockMode.None : CursorLockMode.Locked;
        Cursor.visible = visible;
    }

    public void Pause()
    {
        if (finished)
            return;

        SetPause(true);
        SetCursor(true);
        pausePanel.OpenPanel();
    }

    public void Resume()
    {
        SetPause(false);
        SetCursor(false);
        pausePanel.ClosePanel();
    }

    public void Finish()
    {
        if (!finished)
        {
            finished = true;
            SetCursor(true);
            finishPanel.OpenPanel();
        }
    }
}
