using DG.Tweening;
using Rewired;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class TitleScreenManager : MonoBehaviour
{
    [FMODUnity.EventRef]
    [SerializeField]
    private string musicRef = null;

    [SerializeField]
    private FMODUnity.StudioEventEmitter _btnEmitter1 = null;

    [SerializeField]
    private FMODUnity.StudioEventEmitter _btnEmitter2 = null;

    [SerializeField]
    private GameObject _defaultSelectedGO = null;

    [SerializeField]
    private Image _fadePanel = null;

    private Player _player;
    private FMOD.Studio.EventInstance _musicState;

    private void Awake()
    {
        FMODUnity.RuntimeManager.CoreSystem.setDSPBufferSize(512, 4); // default is 1024/4
        _musicState = FMODUnity.RuntimeManager.CreateInstance(musicRef);
        _musicState.start();

        ReInput.ControllerConnectedEvent += OnControllerConnected;
        ReInput.ControllerDisconnectedEvent += OnControllerDisconnected;
    }

    private void Start()
    {
        _fadePanel.enabled = true;
        _fadePanel.DOFade(0f, 1f).SetEase(Ease.InQuad);

        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }

    private void OnDestroy()
    {
        // Unsubscribe from events
        ReInput.ControllerConnectedEvent -= OnControllerConnected;
        ReInput.ControllerDisconnectedEvent -= OnControllerDisconnected;

        _musicState.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
        _musicState.release();
    }

    // This function will be called when a controller is connected
    private void OnControllerConnected(ControllerStatusChangedEventArgs args)
    {
        EventSystem.current.SetSelectedGameObject(_defaultSelectedGO);
    }

    // This function will be called when a controller is fully disconnected
    private void OnControllerDisconnected(ControllerStatusChangedEventArgs args)
    {
        EventSystem.current.SetSelectedGameObject(null);
    }

    public void StartGame()
    {
        _btnEmitter2.Play();
        _fadePanel.DOFade(1f, 2f).OnComplete(() =>
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        });
    }

    public void QuitGame()
    {
#if UNITY_EDITOR
        _btnEmitter2.Play();
        UnityEditor.EditorApplication.isPlaying = false;
#else
        _btnEmitter2.Play();
        Application.Quit();
#endif
    }

    public void ButtonHighlight()
    {
        _btnEmitter1.Play();
    }

}
