using System;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public sealed class MainMenuController : MonoBehaviour
{
    [SerializeField]
    private Profile profile = null;
    [SerializeField]
    private Text currentPlayerStatus = null;
    [SerializeField]
    private Button continueButton = null;
    [SerializeField]
    private Button newGameButton = null;
    [SerializeField]
    private Button exitButton = null;
    [SerializeField]
    private string gameSceneName = "game";

    private void ContinueGame()
    {
        SceneManager.LoadScene(gameSceneName);
    }

    private void StartNewGame()
    {
        profile.CreateNewPlayer();
        SceneManager.LoadScene(gameSceneName);
    }

    private void ExitGame()
    {
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#endif
        Application.Quit();
    }


    private void Start()
    {
        continueButton.onClick.AddListener(ContinueGame);
        newGameButton.onClick.AddListener(StartNewGame);
        exitButton.onClick.AddListener(ExitGame);

        profile.LoadPlayer();
        continueButton.interactable = profile.SavedPlayer != null;
        SetStatus(profile.SavedPlayer);
    }

    private void SetStatus(Player player)
    {
        if (player == null)
        {
            currentPlayerStatus.text = string.Empty;
            return;
        }
        var stantion = player.CurrentPoint.Stantion;
        currentPlayerStatus.text = $"pilot: {player.Name}\n{stantion.Name} ({stantion.TypeId})\ncredits: {player.Credits}";
    }

    private void OnDestroy()
    {
        continueButton.onClick.AddListener(ContinueGame);
        newGameButton.onClick.AddListener(StartNewGame);
        exitButton.onClick.AddListener(ExitGame);
    }
}
