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

public class Health : MonoBehaviour
{
    public Ownership owner;
    [Header("State")]
    public bool alive = true;
    public float maxHp = 100;
    public float hp = 100;

    [Header("Regeneration")]
    public Ticker regen = new Ticker(1);
    public float hpRegen = 1;

    [Header("Invulnerability")]
    [SerializeField] private float invulTime = 3f;
    private Ticker invulTicker;
    private bool invulnerable = true;

    void Awake() {
        invulTicker = new Ticker(invulTime);
        invulTicker.onTick.AddListener(DropInvul);
    }

    private void Start()
    {
        regen.onTick.AddListener(() => ChangeHealth(hpRegen));

        // var trueHp = hp;
        // hp = 0;
        ChangeHealth(hp);
    }
    private void Update()
    {
        if (!alive) return;
        regen.Tick(Time.deltaTime);
        if(invulnerable)
            invulTicker.Tick(Time.deltaTime);
    }

    private void DropInvul() {
        this.invulnerable = false;
    }

    public void ChangeHealth(float delta)
    {
        var prevHp = hp;
        if(!invulnerable)
            hp += delta;

        if (hp <= 0)
        {
            if(this.owner == Ownership.ENEMY) {
                PlayerManager.I.IncrementKills();
            }
            else if(this.owner == Ownership.PLAYER) {
                PlayerManager.I.Reset();
            }
            alive = false;
            hp = 0;

            var e = new DeathEvent() { health = this };
            Event.Of<DeathEvent>.Execute(gameObject, e);
            Event.Of<DeathEvent>.Execute(e);
            return;
        }

        if (hp > maxHp)
            hp = maxHp;

        if (!Mathf.Approximately(prevHp, hp))
        {
            var e = new HealthUpdateEvent()
            {
                health = this,
                prevHp = prevHp,
                rawDelta = delta
            };
            Event.Of<HealthUpdateEvent>.Execute(gameObject, e);
            Event.Of<HealthUpdateEvent>.Execute(e);
        }
    }
}
