using UnityEngine;

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

        private Rigidbody2D rb2;
        private Vector2 lastVel;
        private float stunnedUntil;

        void TakeHit(HitInfo hit)
        {
            stunnedUntil = Mathf.Max(stunnedUntil, Time.fixedTime + hit.StunTime);
        }

        void OnTriggerEnter2D(Collider2D col)
        {
            if (DoesntHitWhenStunned && stunnedUntil >= Time.fixedTime)
                return;

            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);
            if(hurt.LocalHitOnly)
                col.transform.parent.SendMessage("TakeHit", HitInfo, SendMessageOptions.DontRequireReceiver);
            else
                col.transform.root.BroadcastMessage("TakeHit", HitInfo, SendMessageOptions.DontRequireReceiver);
            transform.root.BroadcastMessage("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>();
        }
    }
}