using Unicorn.Hitbox;
using UnityEngine;

namespace Unicorn
{
    public partial class LivingEntity : MonoBehaviour
    {
        public float maxHealth = 20.0f;
        public float health = 20.0f;
        public GameObject hpBarPrefab;
        
        
        protected bool Invulnerable = false;
        
        private Rigidbody2D Rb { get; set; }
        private HpBar _hpBar;

        protected void Start()
        {
            Rb = TryGetComponent(out Rigidbody2D rb) ? rb : null;
            var hpBar = Instantiate(hpBarPrefab, transform);
            hpBar.TryGetComponent(out _hpBar);
        }

        public void Damage(DamageInfo info)
        {
            if (Invulnerable) return;
            health -= info.Damage;
            OnDamaged(info);
            OnKnockback(info);
            if (health <= 0.0f) OnDeath();
        }


        protected virtual void OnDeath() { }


        protected virtual void OnDamaged(DamageInfo info)
        {
            if (_hpBar) _hpBar.UpdateHealth();
        }

        protected virtual void OnKnockback(DamageInfo info)
        {
            
            var dir = transform.position - info.HitPoint;
            Rb.AddForce(dir.normalized * info.KnockbackForce, ForceMode2D.Impulse);
        }
    }
}
