using EscapeRoomEngine.Engine.Runtime.Utilities;
using NaughtyAttributes;
using UnityEngine;

namespace EscapeRoomEngine.Portal.Runtime
{
    /// <summary>
    /// The portal collider is responsible for detecting <see cref="PortalDriver"/>s that come close to this portal.
    /// </summary>
    [RequireComponent(typeof(Collider))]
    public class PortalCollider : MonoBehaviour
    {
        [BoxGroup("Internal")] [SerializeField] private Portal portal;
        
        private void Awake()
        {
            // check whether the collider is set up correctly
            if (!GetComponent<Collider>().isTrigger) throw new EngineException("Collider must be a trigger.");
        }

        private void OnTriggerEnter(Collider other)
        {
            if (portal.Connected)
            {
                var portalDriver = other.GetComponent<PortalDriver>();
                if (portalDriver && !portal.closePortalDrivers.Contains(portalDriver))
                {
                    portal.StartTrackingDriver(portalDriver, portal.CalculateSide(portalDriver.transform));
                }
            }
        }

        private void OnTriggerExit(Collider other)
        {
            if (portal.Connected)
            {
                var portalDriver = other.GetComponent<PortalDriver>();
                if (portalDriver)
                {
                    portal.StopTrackingDriver(portalDriver);
                }
            }
        }
    }
}