using EscapeRoomEngine.Engine.Runtime.Modules;
using EscapeRoomEngine.Engine.Runtime.Modules.State;
using EscapeRoomEngine.Engine.Runtime.Utilities;
using NaughtyAttributes;
using Station46.Modules.Hoop.Scripts;
using Station46.Scripts;
using UnityEngine;

namespace Station46.Modules.Button_Stand.Scripts
{
    public class TimedButtonStand : StatePuzzle
    {
        [BoxGroup("Internal")] [SerializeField] private HoloButton button;
        [BoxGroup("Internal")] [SerializeField] private Emission standLight;

        private ButtonHoop _hoop;

        protected override void Start()
        {
            base.Start();
            
            PuzzleEvent += (_, type) =>
            {
                // ReSharper disable once SwitchStatementMissingSomeEnumCasesNoDefault
                switch (type)
                {
                    case PuzzleEventType.Restarted:
                        standLight.color = EscapeRoomEngine.Engine.Runtime.Engine.Theme.puzzleColor.hdr;
                        button.hideWhenDisabled = true;
                        button.Enable();
                        button.Disable();
                        break;
                    case PuzzleEventType.Solved:
                        standLight.color = EscapeRoomEngine.Engine.Runtime.Engine.Theme.solvedColor.hdr;
                        button.hideWhenDisabled = false;
                        button.Enable();
                        button.Disable();
                        break;
                }
            };

            button.ButtonEvent += (_, type) =>
            {
                if (type == ButtonEventType.Pressed)
                {
                    Solve();
                }
            };
        }
        
        public override void SetModule(Module module)
        {
            base.SetModule(module);
            
            // The hoop requires a related dispenser module
            // We use the second slot because the first slot is reserved for the platform
            var secondRelatedModule = Module.relatedModules[1];
            if (secondRelatedModule.State is ButtonHoop hoop)
            {
                hoop.Button.ButtonEvent += (_, type) =>
                {
                    if (type == ButtonEventType.Pressed)
                    {
                        button.Enable();
                    }
                    else
                    {
                        button.Disable();
                    }
                };
            }
            else
            {
                throw new EngineException($"{this} was not assigned a related button hoop.");
            }
        }
    }
}