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

public class SettingsMenu : MonoBehaviour
{
    public AudioMixer audioMixer;
    public Slider volumeSlider;
    public Toggle fullscreenToggle;
    public TMP_Dropdown qualityDropdown;
    public TMP_Dropdown resolutionDropdown;
    public GameObject mainMenu;
    [SerializeField] private TextMeshProUGUI volumeText;


    Resolution[] resolutions;
    int currentResolutionIndex;

    void Start() 
    {
        if (volumeSlider != null)
        {
            volumeSlider.onValueChanged.AddListener(setVolume);
        }
        if (fullscreenToggle != null)
        {
            fullscreenToggle.onValueChanged.AddListener(setFullscreen);
        }
        if (qualityDropdown != null)
        {
            qualityDropdown.onValueChanged.AddListener(setQuality);
        }
        if (resolutionDropdown != null)
        {
            resolutions = Screen.resolutions;

            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.width && resolutions[i].height == Screen.height) currentResolutionIndex = i;
            }
            resolutionDropdown.AddOptions(options);
            resolutionDropdown.value = currentResolutionIndex;
            resolutionDropdown.RefreshShownValue();
            
            resolutionDropdown.onValueChanged.AddListener(setResolution);
        }
    }

    public void ContinueButton()
    {
        gameObject.SetActive(false);
        mainMenu.SetActive(true);
    }

    public void setVolume(float vol)
    {
        float mixerVolume = Mathf.Lerp(-80f, 0f, vol);
        audioMixer.SetFloat("Volume", mixerVolume);
        volumeText.text = Mathf.RoundToInt(vol * 100) + "%";
    }
    public void setQuality(int qualityIndex)
    {
        QualitySettings.SetQualityLevel(qualityIndex);
    }

    public void setFullscreen(bool isFullscreen)
    {
        Screen.fullScreen = isFullscreen;
    }
    public void setResolution(int resolutionIndex)
    {
        Screen.SetResolution(resolutions[resolutionIndex].width, resolutions[resolutionIndex].height, FullScreenMode.FullScreenWindow);
    }
}
