using Unicorn.Hitbox;
using UnityEngine;

namespace Unicorn
{
    public partial class LivingEntity : MonoBehaviour
    {
        public float health = 20.0f;
        private Rigidbody2D Rb { get; set; }
        private bool _invulnerable = false;

        private void Start()
        {
            Rb = TryGetComponent(out Rigidbody2D rb) ? rb : null;
        }

        private void OnTriggerEnter2D(Collider2D other)
        {
            if (Rb == null) return;
            var transformPosition = other.transform.position - transform.position;
            Rb.linearVelocity = Vector2.zero;
            Rb.AddForce(transformPosition.normalized * health, ForceMode2D.Impulse);
        }

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


        protected virtual void OnDeath() { }


        protected virtual void OnDamaged(DamageInfo info) { }

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