using System;
using UnityEngine;
using TMPro;
using GatherAndDefend.Events;

public class TooltipText : MonoBehaviour
{
    private TooltipManager _tooltipManager;
    [SerializeField]
    private GameObject _tooltipPanel;
    [SerializeField]
    private TextMeshProUGUI _tooltipDescription;
    [SerializeField]
    private TextMeshProUGUI _tooltipHp;
    [SerializeField]
    private TextMeshProUGUI _tooltipDmg;
    [SerializeField]
    private TextMeshProUGUI _tooltipAttackSpeed;
    private const string EMPTY_STRING = "";

    private void Start()
    {
        _tooltipManager = TooltipManager.Instance;
        EventAggregator.Instance.GetEvent<TooltipChangedEvent>().Attach(OnEventUpdate);
    }

    private void OnDestroy()
    {
        EventAggregator.Instance.GetEvent<TooltipChangedEvent>().Detach(OnEventUpdate);
    }

    private void OnEventUpdate()
    {
        if (_tooltipManager.TooltipVisibility)
        {
            _tooltipPanel.SetActive(true);
            _tooltipDescription.text = _tooltipManager.Description;
            _tooltipHp.text = (_tooltipManager.Hp.Equals("0") ? ("Intouchable") 
                : $"({_tooltipManager.Hp} hp) ({_tooltipManager.Damage} atk)");

            float dmg = float.Parse(_tooltipManager.Damage);
            float atkSpeed = float.Parse(_tooltipManager.AttackSpeed);
            float dps = dmg / atkSpeed;

            _tooltipDmg.text = (_tooltipManager.Damage.Equals("0")) ? "" 
                : $"{dps:0.00} dps";
        }
        else
        {
            _tooltipPanel.SetActive(false);
            _tooltipDescription.text = EMPTY_STRING;
            _tooltipHp.text = EMPTY_STRING;
            _tooltipDmg.text = EMPTY_STRING;
            _tooltipAttackSpeed.text = EMPTY_STRING;
        }
    }
}
