using System.Collections.Generic;
using Intrepid.Diagnostics;
using Intrepid.FSM;

namespace Intrepid.Gameplay.Journey
{
    public sealed class StageStateMachine
    {
        private FStateMachine<StageTag, StageLoadingService> StateMachine { get; } = new();
        private IState<StageTag, StageLoadingService> CurrentState => StateMachine.GetCurrentState();
        
        public StageTag CurrentStageTag => CurrentState.GetStateKey();
        public bool IsLoadingFinished => CurrentState.Implementation().IsLoadingFinished;
        public bool IsRunning => StateMachine.IsRunning;

        public void LoadMachine(IEnumerable<StageTag> stageTags)
        {
            if (StateMachine.IsRunning)
            {
                DLogger.LogError("stage state machine is already running (are we changing state outside JourneyManager?");
                return;
            }
            foreach (var stageTag in stageTags)
            {
                StateMachine.AddState(new StageLoadingService(stageTag));
            }
        }

        public void InitMachine(StageTag stageTag)
        {
            if (StateMachine.IsRunning) return;
            StateMachine.InitializeWith(stageTag);
            StateMachine.Start();
        }
        
        public void ChangeState(StageTag stageTag)
        {
            StateMachine.ChangeState(stageTag);
        }

        public void TearDown()
        {
            if (!StateMachine.IsRunning) return;
            StateMachine.GetCurrentState().OnExitState();
        }
    }
}