using System.Collections.Generic;
using Intrepid.Diagnostics;
using Intrepid.GameManagers;
using Intrepid.Gameplay.Journey.Messages.Events;
using Intrepid.Gameplay.Prototyping;
using Intrepid.SimpleEvents;
using Intrepid.Utilities;
using Sirenix.OdinInspector;
using UnityEngine;

namespace Intrepid.Gameplay.Journey.Stages
{
    public class StageManager : EventListener
    {
        [GroupConfigurations, SerializeField] private StageTag stageTag;
        [GroupDebug, SerializeField] private List<InteractableSocketModelPrototype> sockets;
        
        private Dictionary<string, InteractableSocketModelPrototype> SocketMap { get; } = new();
        
        public StageTag StageTag => stageTag;

        protected override void InitializeVariables()
        {
            Refresh();
        }

        protected override void OnBootstrap()
        {
        }

        protected override void Subscriptions()
        {
            Subscribe<ChangeStageLandingOnStageStepEvent>(e =>
            {
                if (SocketMap.TryGetValue(e.DestinyEndpoint, out var stageSocket))
                {
                    Proxy.Instance.EventBus.Raise(new StageDispatchDeploymentPointEvent
                    {
                        DeploymentPoint = stageSocket.DeploymentPoint,
                        DeploymentDirection = stageSocket.DeploymentDirection,
                    });
                    return;
                }
                
                DLogger.LogError($"No stage socket found for endpoint {e.DestinyEndpoint}");
            });
        }

        [GroupDebug, Button(ButtonSizes.Medium)]
        private void Refresh()
        {
            sockets.Clear();
            foreach (var stageSocket in GetComponentsInChildren<InteractableSocketModelPrototype>())
            {
                stageSocket.StageManager = this;
                sockets.Add(stageSocket);
                SocketMap.Add(stageSocket.EndpointId, stageSocket);
            }
        }
    }
}