using UnityEngine;

namespace ScrambleKit.Hits
{
    public class HitBox : MonoBehaviour
    {
        public bool KnockBackFromVelocity = true;
        public HitInfo HitInfo;

        private Rigidbody2D rb2;
        private Vector2 lastVel;

        void OnTriggerEnter2D(Collider2D col)
        {
            HurtBox hurt = col.GetComponent<HurtBox>();
            if (hurt == null)
                return;

            Vector2 dir = GetKnockBackDir(col);
            HitInfo.Direction = dir;

            // Debug.Log(transform.root.name + "'s " + name + " hitting " + col.transform.root.name + " on its " + col.name + " and the knockback dir is " + dir);
            col.transform.root.SendMessage("TakeHit", HitInfo, SendMessageOptions.DontRequireReceiver);
            transform.root.SendMessage("LandedHit", HitInfo, SendMessageOptions.DontRequireReceiver);
        }

        private Vector2 GetKnockBackDir(Collider2D other)
        {
            if(KnockBackFromVelocity && rb2 != null)
            {
                return lastVel.normalized;
            }
            else
            {
                return (other.transform.position - transform.position).normalized;
            }
        }

        void FixedUpdate()
        {
            if (KnockBackFromVelocity && rb2 != null)
            {
                lastVel = rb2.velocity;
            }
        }

        void Start()
        {
            rb2 = transform.root.GetComponent<Rigidbody2D>();
        }
    }
}