using UnityEngine;

using UPG.Debugging;

namespace BR.BattleRoyale
{
    public class BoostGate : MonoBehaviour
    {
        #region COMPONENTS
        Collider m_collider;
        #endregion

        #region INSPECTOR FIELDS
        [Header("Options")]
        [SerializeField] [Range(5, 50)] float m_boostPower = 20;

        [Header("Debug")]
        [SerializeField] DebugChannel m_debugChannel = null;
        #endregion

        #region DEFAULT METHODS
        void OnValidate()
        {
            if (Application.isPlaying)
                return;

            if (!GetComponent<Collider>())
                gameObject.AddComponent<BoxCollider>();
        }
        void Awake()
        {
            m_collider = GetComponent<Collider>();

            if (!m_collider)
                Destroy(this);
        }
        void OnTriggerEnter(Collider other)
        {
            if (!other.GetComponent<Player>() && !other.GetComponent<Rigidbody>())
                return;

            if (Vector3.Distance(other.transform.position, transform.position) < m_collider.bounds.extents.x / 2)
                return;

            if (!other.GetComponent<Player>())
            {
                other.transform.position = transform.position;
                other.transform.forward = transform.forward;
            }
            else
            {
                other.GetComponent<CharacterController>().enabled = false;
                other.transform.position = transform.position;
                other.GetComponent<CharacterController>().enabled = true;
            }

            if (other.GetComponent<BattleRoyale.Spells.Spell>())
                other.GetComponent<BattleRoyale.Spells.Spell>().BoostSpell(m_boostPower * 10, 1);

            m_debugChannel?.Raise(this, "Boosting " + other.name + " with a power of " + m_boostPower.ToString() + "!");

            Player _controller = other.GetComponent<Player>();

            if (_controller)
            {
                _controller.Boost(transform.forward * m_boostPower * 40);

                return;
            }

            Rigidbody _rb = other.GetComponent<Rigidbody>();

            if (_rb)
            {
                if (_rb.velocity != transform.forward * m_boostPower)
                    _rb.AddForce(transform.forward * m_boostPower, ForceMode.VelocityChange);

                if (_rb.velocity.normalized != transform.forward)
                    _rb.velocity = transform.forward * _rb.velocity.magnitude;

                if (_rb.transform.forward != transform.forward)
                    _rb.transform.forward = transform.forward;

                return;
            }
        }
        void OnDrawGizmosSelected()
        {
            m_debugChannel?.DrawLine(transform.position, transform.position + (transform.forward * m_boostPower * 0.1f));
            m_debugChannel?.DrawPrism(transform.position + (transform.forward * m_boostPower * 0.1f), transform.forward);
        }
        #endregion
    }
}