using System.Collections.Generic;
using Intrepid.GameManagers;
using Intrepid.Gameplay.Entities.Player.PDA.Events;
using Intrepid.Gameplay.Entities.Player.PDA.Inputs;
using Intrepid.Structures;
using Intrepid.Utilities;
using UnityEngine;

namespace Intrepid.Gameplay.Entities.Player.PDA.UI
{
    public class PDAApplicationSelectionUI : MonoBehaviour, IPDAApplicationUpdater
    {
        [SerializeField, GroupInjections] private PDASectionsUI sections;
        [SerializeField, GroupInjections] private PDAContentsUI contents;

        public bool IsLoading => sections.IsLoadingContents;
        private SDictionary<PDASectionTag, List<PDAContentTag>> ContentTagsBySectionTag { get; } = new();

        public void WhenStarting(ParameterStore parameters)
        {
            sections.WhenStarting(parameters);
            contents.WhenStarting(parameters);
        }
        
        public void UpdateApplication(PDAInputs inputs)
        {
            if (inputs.Cancel())
            {
                Proxy.Instance.EventBus.Raise(new PDADeviceShutdownEvent());
                return;
            }
            
            if (!sections.UpdateSections(inputs)) return;
            if (!contents.UpdateContents(inputs)) return;

            if (inputs.Enter())
            {
                Proxy.Instance.EventBus.Raise(new PDAEnterApplicationEvent
                {
                    ContentTag = contents.CurrentContentFocus.ContentTag, 
                });
            }
        }

        public void LateUpdateApplication(PDAInputs inputs)
        {
        }

        public void WhenPreparingSystemBoot()
        {
            sections.WhenPreparingSystemBoot();
            contents.WhenPreparingSystemBoot();
        }
        
        public void WhenFinishing()
        {
            sections.WhenFinishing();
            contents.WhenFinishing();
        }

        public void PrepareEnvironment(List<PDAContentTag> availableContentTags)
        {
            ContentTagsBySectionTag.Clear();
            foreach (var contentTag in availableContentTags)
            {
                if (ContentTagsBySectionTag.TryGetValue(contentTag.SectionTag, out var contentTags))
                {
                    contentTags.Add(contentTag);
                }
                else
                {
                    contentTags = new List<PDAContentTag>
                    {
                        Capacity = contents.ContentsCapacity,
                    };
                    contentTags.Add(contentTag);
                    ContentTagsBySectionTag.Add(contentTag.SectionTag, contentTags);
                }
            }

            sections.PrepareEnvironment(ContentTagsBySectionTag);
        }
    }
}