using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthUpdater : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }


    public event System.EventHandler HealthComponentDied;

    // Update is called once per frame
    void Update()
    {
        HealthComponent[] hcs = FindObjectsOfType<HealthComponent>();
        foreach(HealthComponent hc in hcs)
        {
            if (hc.Health > 0.0f)
            {
                if (hc.PendingDamage > 0.0f)
                {
                    if (hc.BarkskinActive)
                    {
                        hc.gameObject.FloatText("BLOCK");
                    }
                    else
                    {
                        hc.Health -= hc.PendingDamage;
                        hc.gameObject.FloatText("-" + hc.PendingDamage);
                    }

                    hc.PendingDamage = 0.0f;

                    if (hc.Health <= 0.0f)
                    {
                        // health component is about to die, notify the monster factory
                        GetComponent<MonsterFactory>().HealthComponentDied(hc);

                        // Notify listeners
                        HealthComponentDied?.Invoke(hc, null);

                        Object.Destroy(hc.GetComponent<SwingTimerComponent>());

                        // Play death animation
                        if (hc.GetComponent<Animator>() != null)
                            hc.GetComponent<Animator>().SetTrigger("Die");

                        // Queue for destroying
                        if (hc.GetComponent<Team>().team == TeamValue.Enemy)
                            Object.Destroy(hc.gameObject, 1.0f);
                    }

                }

                if (hc.PendingHeal > 0.0f)
                {
                    hc.Health = Mathf.Min(hc.MaxHealth, hc.Health + hc.PendingHeal);
                    hc.gameObject.FloatText("+" + hc.PendingHeal);
                    hc.PendingHeal = 0.0f;
                }

            }
        }

    }
}
