using System;
using Intrepid.Gameplay.Codex.UI.Controllers;
using Intrepid.Gameplay.Codex.Visual;
using Intrepid.Gameplay.Codex.Visual.Events;
using Intrepid.SimpleEvents;

namespace Intrepid.Gameplay.Codex.UI
{
    public class CodexWindowUI : ManagedWindowUI, IWindowLifecycle
    {
        private CodexControllerUI[] Controllers { get; set; }
        private EventBus LocalBus { get; } = new();

        protected override void InitializeVariables()
        {
            Controllers = GetComponentsInChildren<CodexControllerUI>(true);
        }

        protected override void OnBootstrap()
        {
            var ctx = new CodexWindowContext(LocalBus, this);
            foreach (var controller in Controllers)
            {
                if (controller.IsNull()) continue;
                controller.BindToWindow(ctx);
            }
        }

        protected override void Subscriptions()
        {
            Subscribe<CodexVisualChangedEvent>(e =>
            {
                foreach (var controller in Controllers)
                {
                    if (controller.IsNull()) continue;
                    controller.ApplyCodexVisuals(e.Context);
                }
            });
        }
        
        public virtual void BeforeOpen()
        {
            var visualContext = CodexVisualService.Instance.CurrentContext;
            foreach (var controller in Controllers)
            {
                if (controller.IsNull()) continue;
                controller.ApplyCodexVisuals(visualContext);
                controller.BeforeOpen();
            }
        }
        
        public virtual void AfterOpen()
        {
            foreach (var controller in Controllers)
            {
                if (controller.IsNull()) continue;
                controller.AfterOpen();
            }
        }

        public virtual void BeforeClose()
        {
            foreach (var controller in Controllers)
            {
                if (controller.IsNull()) continue;
                controller.BeforeClose();
            }
        }
        
        public virtual void AfterClose()
        {
            foreach (var controller in Controllers)
            {
                if (controller.IsNull()) continue;
                controller.AfterClose();
            }
        }

        public virtual void EnableInput()
        {
            foreach (var controller in Controllers)
            {
                if (controller.IsNull()) continue;
                controller.EnableInput();
            }
        }

        public virtual void DisableInput()
        {
            foreach (var controller in Controllers)
            {
                if (controller.IsNull()) continue;
                controller.DisableInput();
            }
        }
    }
    
}