using System;
using Intrepid.Core;
using Intrepid.Core.GameState;
using Intrepid.SimpleEvents;
using Intrepid.Theatre.BackStage;
using Intrepid.Theatre.BackStage.Events;
using Intrepid.Theatre.Curtain;
using Intrepid.Utilities;
using TMPro;
using UnityEngine;

namespace Temporary
{
    public class FakeSceneManager : EventListener
    {
        [SerializeField] private GameState nextState = GameState.Gameplay;
        [SerializeField] private float delay = 2f;
        [SerializeField] private CurtainTypeTag curtainType;
        [SerializeField] private string sceneName;
        [SerializeField] private TextMeshProUGUI textMeshPro;
        [SerializeField] private bool startOnBootstrap;
        [SerializeField] private BackStageProcessorMonoBehaviour backStageProcessor;

        private Timer Timer { get; } = new();

        protected override void InitializeVariables()
        {
        }

        protected override void OnBootstrap()
        {
            if (startOnBootstrap)
            {
                Timer.Start();
            }
        }

        protected override void Subscriptions()
        {
            Subscribe<BackStageWorkIsCompletedEvent>(WhenBackStageWorkIsCompleted);
        }

        private void WhenBackStageWorkIsCompleted(BackStageWorkIsCompletedEvent e)
        {
            if (Timer.IsNotRunning) Timer.Start();
        }

        private void Update()
        {
            if (Timer.IsNotRunning) return;
            Timer.Update(Time.deltaTime);
            if (textMeshPro.IsNotNull()) textMeshPro.text = $"{sceneName} -> {nextState}\n{delay - Timer.RunningTime:F2}";
            if (!Timer.Check(delay)) return;
            Timer.Stop();
            GameManager.Instance.ChangeGameStateTo(nextState, curtainType, new BackStageProcessorAggregator(backStageProcessor));
        }
    }
}