using System.Threading;
using Cysharp.Threading.Tasks;
using QuizPleaseTest.Boot.States;
using QuizPleaseTest.Common.Services;
using QuizPleaseTest.Common.StateMachine;

namespace QuizPleaseTest.Boot.Flow
{
    public class BootFlowService : Service, IBootFlowService
    {
        private readonly IStatesController<BootStateCode> _statesController;

        public BootFlowService(IStatesController<BootStateCode> statesController)
        {
            _statesController = statesController;
        }

        public override async UniTask InitializeAsync(CancellationToken ct)
        {
            await RunFlowAsync(ct);
        }

        public override UniTask ReleaseAsync(CancellationToken ct)
        {
            return UniTask.CompletedTask;
        }

        private async UniTask RunFlowAsync(CancellationToken ct)
        {
            await _statesController.EnterStateAsync(BootStateCode.Splash, ct);
            await _statesController.EnterStateAsync(BootStateCode.Load, ct);

            while (!ct.IsCancellationRequested)
            {
                await _statesController.EnterStateAsync(BootStateCode.Menu, ct);
                await _statesController.EnterStateAsync(BootStateCode.Load, ct);
            }

            ct.ThrowIfCancellationRequested();
        }
    }
}
