using System.Collections.Generic;
using UnityEngine;

public class GraphicsSettings : MonoBehaviour
{
    private static Resolution[] _resolutions;

    public static Resolution[] RESOLUTIONS
    {
        get
        {
            if ( _resolutions != null )
            {
                return _resolutions;
            }

            var resList = new List<Resolution>();
            Resolution last = new Resolution();
            
            foreach (var res in Screen.resolutions)
            {
                if ( res.height != last.height || res.height != last.height )
                {
                    resList.Add(res);
                    last = res;
                }
            }

            _resolutions = resList.ToArray();
            return _resolutions;
        }
    }
    
    private Resolution _currentResolution;
    private FullScreenMode _fullscreenMode;

    [SerializeField]
    private PlayerPrefValue _resolutionPlayerPref;
    
    [SerializeField]
    private PlayerPrefValue _fullscreenPlayerPref;

    private const FullScreenMode FULLSCREEN = FullScreenMode.FullScreenWindow;
    private const FullScreenMode WINDOWED = FullScreenMode.Windowed;

    private void Awake()
    {
        _currentResolution = RESOLUTIONS[ _resolutionPlayerPref.GetInt( RESOLUTIONS.Length - 1 ) ];
        _fullscreenMode
            = ( _fullscreenPlayerPref.GetInt( 1 ) > 0 )
                ? FULLSCREEN
                : WINDOWED;
        
        UpdateGraphics();

        _resolutionPlayerPref.OnIntSet.AddListener(SetResolution);
        _fullscreenPlayerPref.OnIntSet.AddListener( ( value ) => { SetFullscreen( value > 0 ); } );
    }

    private void SetResolution( int value )
    {
        _currentResolution = RESOLUTIONS[ value ];
        
        UpdateGraphics();
    }

    private void SetFullscreen( bool value )
    {
        _fullscreenMode
            = value
                ? FULLSCREEN
                : WINDOWED;
        
        UpdateGraphics();
    }

    private void UpdateGraphics()
    {
        Screen.SetResolution(
            _currentResolution.width, 
            _currentResolution.height, 
            _fullscreenMode
        );
    }
}
