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

namespace UI
{
    using Managers;

    public class GUIController : Utils.SingletonComponent<GUIController>
    {
        [SerializeField] private GameObject loginWindow;
        [Header("Top Info Panel")]
        [SerializeField] private Image logo;
        [SerializeField] private TextMeshProUGUI agencyText;
        [SerializeField] private TextMeshProUGUI budgetText;
        [SerializeField] private TextMeshProUGUI dateTimeText;
        [SerializeField] private Button exitButton;

        DataManager dataManager;

        void Start()
        {
            dataManager = DataManager.Instance;

            dateTimeText.gameObject.SetActive(false);

            dataManager.SubscribeOnLoad(delegate
            {
                loginWindow.SetActive(!dataManager.HasAccount);
                logo.sprite = dataManager.Logo;
                agencyText.text = dataManager.AgencyName;
                budgetText.text = dataManager.Budget.ToString();
            });

            dataManager.SubscribeOnBudgetChange(UpdateBudgetText);

            Calendar.Instance.SubscribeOnTimer(UpdateDateTimeText);

            exitButton.onClick.AddListener(ExitGame);
        }

        public void InitTopPanel(Sprite sp, string agencyName, int budget)
        {
            logo.sprite = sp;
            agencyText.text = agencyName;
            budgetText.text = budget.ToString();            
        }

        private void UpdateBudgetText(int budget) => budgetText.text = budget.ToString();

        private void UpdateDateTimeText(System.DateTime dateTime)
        {
            if(!dateTimeText.gameObject.activeInHierarchy)
                dateTimeText.gameObject.SetActive(true);

            dateTimeText.text = dateTime.ToString("MMMM, ddd dd, HH:mm");
        }

        public void ExitGame()
        {
            Sound.SoundController.Instance.Play(SoundType.UIClick);
            Application.Quit();

#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#endif
        }
    }
}