using System;
using System.Collections;
using TMPro;
using UnityEngine;

public class HealthChangedText : MonoBehaviour
{
    [SerializeField] Battler _battler;
    [SerializeField] TMP_Text _text;

    void Awake()
    {
        if (_battler == null)
            _battler = GetComponentInParent<Battler>();
    }

    void OnValidate()
    {
        _battler = GetComponentInParent<Battler>();
        _text = GetComponent<TMP_Text>();
    }

    void OnEnable()
    {
        _battler.TookHit += ShowHitText;
        _text.SetText(String.Empty);
    }

    void OnDisable() => _battler.TookHit -= ShowHitText;

    void ShowHitText(int damageTaken, bool wasCrit)
    {
        if (wasCrit)
            _text.SetText($"<color=red><size=42>-{damageTaken}</size></color>");
        else
            _text.SetText($"<color=orange><size=32>-{damageTaken}</size></color>");
        
        StartCoroutine(WaitASecond());
    }

    IEnumerator WaitASecond()
    {
        yield return new WaitForSeconds(1);
        _text.SetText(string.Empty);
    }
}
