using System;
using System.Collections.Generic;
using System.Linq;
using Intrepid.Core.Entities;
using Intrepid.Core.Tags;
using Intrepid.Diagnostics;
using Intrepid.Gameplay.Journey;
using Intrepid.Utilities;
using UnityEngine;

namespace Intrepid.Gameplay.Prototyping.Sockets
{
    public class StageSocketChangeTrigger : EntityTrigger
    {
        [GroupInjections, SerializeField] private InteractableSocketModelPrototype socket;

        private BoxCollider BoxCollider => MainCollider as BoxCollider;
        
        protected override void WhenRaiseEnterEvent(Collider other, EntitySensor entitySensor, List<BehaviourTag> behaviourTags)
        {
            var stageId = socket.StageId;
            var endpointId = socket.EndpointId;
            if (!JourneyService.Instance.TryGetJConnections(stageId, endpointId, out var jConnections))
            {
                DLogger.LogWarn($"Stage {stageId} has invalid endpoint: {endpointId}");
                return;
            }
            if (jConnections.Count > 1)
            {
                DLogger.LogWarn($"Stage {stageId} has multiple connections from endpoint: {endpointId}");
                return;
            }
            var destinyEndpoint = GrabDestinyEndpoint(jConnections.First());
            if (!JourneyService.Instance.TryGetStageTagFromEndpoint(destinyEndpoint, out var stageTag))
            {
                DLogger.LogWarn($"Stage {stageId} has invalid endpoint: {endpointId}");
                return;
            }
            JourneyManager.Instance.ChangeStageTo(stageTag, destinyEndpoint);
            DLogger.LogDebug("stage change");
        }

        private string GrabDestinyEndpoint(JConnection jConnection)
        {
            return socket.EndpointId.Equals(jConnection.endpointAId, StringComparison.Ordinal)
                ? jConnection.endpointBId
                : jConnection.endpointAId;
        }

        protected override void WhenRaiseExitEvent(Collider other, EntitySensor entitySensor)
        {
        }
        
#if UNITY_EDITOR
        private void OnDrawGizmos()
        {
            if (BoxCollider is null)
            {
                return;
            }
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireCube(BoxCollider.bounds.center, BoxCollider.bounds.size);
        }
#endif
    }
}