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

public class WinEngine : MonoBehaviour
{    
    public TMPro.TextMeshProUGUI scoreText;

    public BackgroundMusicManager currentBGMManager;
    public MenuAudioManager currentMenuAudioManager;

    private GameObject _lastControlSelected;

    public GameObject shipGO;
    public float flightSpeed;

    private void Awake()
    {
        GameManager.Instance.currentGameState = GameState.WINMENU;
    }

    // Start is called before the first frame update
    void Start()
    {
        // If the BGM manager is present, queue up and play the given track index
        if (currentBGMManager)
        {
            currentBGMManager.StartAudioQueueAndPlay(0);
        }

        scoreText.text = scoreText.text.Replace("{SCORE}", GameManager.Instance.CurrentScore.ToString().PadLeft(9, '0'));
        _lastControlSelected = EventSystem.current.firstSelectedGameObject;
    }

    public void PlayMenuClick()
    {
        if (currentMenuAudioManager)
        {
            currentMenuAudioManager.PlayMenuClick();
        }
    }

    public void MainMenuNav()
    {
        // Play the menu click sound if the audio manager is present
        if (currentMenuAudioManager)
        {
            currentMenuAudioManager.PlayMenuClick();
        }
        SceneManager.LoadSceneAsync("MainMenu");
    }

    public void GameMenuNav()
    {
        // Play the menu click sound if the audio manager is present
        if (currentMenuAudioManager)
        {
            currentMenuAudioManager.PlayMenuClick();
        }
        GameManager.Instance.ResetStats();
        SceneManager.LoadSceneAsync("Game");
    }

    public void Quit()
    {
        // Play the menu click sound if the audio manager is present
        if (currentMenuAudioManager)
        {
            currentMenuAudioManager.PlayMenuClick();
        }

#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else
             Application.Quit();
#endif
    }

    // Update is called once per frame
    void Update()
    {       
        if (shipGO != null)
        {
            shipGO.transform.position += (shipGO.transform.forward * flightSpeed * Time.deltaTime);
            shipGO.transform.Rotate(Vector3.up, flightSpeed * Time.deltaTime * 0.5f);
        }

        float horzIn = Input.GetAxis("Horizontal");
        float vertIn = Input.GetAxis("Vertical");

        if (horzIn != 0 || vertIn != 0)
        {
            if (EventSystem.current.currentSelectedGameObject == null)
            {
                EventSystem.current.SetSelectedGameObject(_lastControlSelected);
            }
            else
            {
                _lastControlSelected = EventSystem.current.currentSelectedGameObject;
            }
        }
    }
}
