using System;
using System.Collections.Generic;
using System.Threading;
using Cysharp.Threading.Tasks;

namespace QuizPleaseTest.Common.StateMachine
{
    public class StatesController<TEnum> : IStatesController<TEnum>
    {
        private readonly IReadOnlyDictionary<TEnum, IState> _states;
        private IState _currentState;
        private bool _hasCurrentState;

        public StatesController(IReadOnlyDictionary<TEnum, IState> states)
        {
            _states = states;
        }

        public async UniTask EnterStateAsync(TEnum code, CancellationToken ct)
        {
            ct.ThrowIfCancellationRequested();

            if (!_states.TryGetValue(code, out IState newState))
            {
                throw new InvalidOperationException($"State is not registered: {code}");
            }

            if (_hasCurrentState)
            {
                await _currentState.ExitAsync(ct);
                _currentState = null;
                _hasCurrentState = false;
            }

            ct.ThrowIfCancellationRequested();

            await newState.EnterAsync(ct);
            _currentState = newState;
            _hasCurrentState = true;
        }
    }
}
