using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Linq;
using UnityEngine.UI;

public class MainMenu : MonoBehaviour{

    [SerializeField] Button settingsButton;
    
    [Space]
    Resolution[] resolutions;
    [SerializeField] TMP_Dropdown resolutionDropdown;
    int currentResolutionIndex;

    [SerializeField] GameObject cutsceneText;
    Animator anim;
    bool onSettingsMenu;

    void Start(){
        anim = GetComponent<Animator>();

        resolutions = Screen.resolutions.Select(resolution => new Resolution { width = resolution.width, height = resolution.height }).Distinct().ToArray();
        resolutionDropdown.ClearOptions();

        List<string> options = new List<string>();
        for (int i = 0; i < resolutions.Length; i++){
            string option = resolutions[i].width + " x " + resolutions[i].height;
            options.Add(option);

            if(resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height){
                currentResolutionIndex = i;
            }
        }

        resolutionDropdown.AddOptions(options);
        resolutionDropdown.value = currentResolutionIndex;
        resolutionDropdown.RefreshShownValue();
    }

    void Update(){
        if (Input.GetKeyDown(KeyCode.Escape) && onSettingsMenu){
            anim.SetTrigger("SettingsMenuExit");
            settingsButton.enabled = true;
            onSettingsMenu = false;
        }
    }

    public void SetQuality(int qualityIndex){
        QualitySettings.SetQualityLevel(qualityIndex);
    }

    public void SetResolution(int resolutionIndex){
        Resolution resolution = resolutions[resolutionIndex];

        Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
    }

    public void SelectModeEnter(){
        if (PlayerPrefs.HasKey("AlreadyPlayed")){
            anim.SetTrigger("SelectModeEnter");
        }else{
            anim.SetTrigger("CutsceneFirstTime");
            StartCoroutine(CutscenePlay());
            PlayerPrefs.SetInt("AlreadyPlayed", 1);
        }
    }

    public void CutsceneEnter(){
        anim.SetTrigger("CutsceneEnter");
        StartCoroutine(CutscenePlay());
    }

    IEnumerator CutscenePlay(){
        yield return new WaitForSeconds(1f);
        cutsceneText.SetActive(true);
    }

    public void SettingsMenuEnter(){
        anim.SetTrigger("SettingsMenuEnter");
        settingsButton.enabled = false;
        StartCoroutine(AccessSettingsMenu());
    }

    public void Quit(){
        Application.Quit();
    }

    IEnumerator AccessSettingsMenu(){
        yield return new WaitForSeconds(1f);
        onSettingsMenu = true;
    }

    public void EasyPlay(){
        SceneLoader.instance.LoadScene(1, SceneLoader.DifficultySelected.Easy);
    }

    public void HardPlay(){
        SceneLoader.instance.LoadScene(1, SceneLoader.DifficultySelected.Hard);
    }
}
