using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using QuizPleaseTest.Boot.Flow;
using QuizPleaseTest.Boot.UI;
using QuizPleaseTest.Common.StateMachine;

namespace QuizPleaseTest.Boot.States
{
    public class MenuState : IState
    {
        private readonly MenuUIView _view;
        private readonly BootStatusUIView _statusView;
        private readonly IMenuRestartSignal _restartSignal;

        public MenuState(MenuUIView view, BootStatusUIView statusView, IMenuRestartSignal restartSignal)
        {
            _view = view;
            _statusView = statusView;
            _restartSignal = restartSignal;
        }

        public async UniTask EnterAsync(CancellationToken ct)
        {
            _statusView.SetStatus("Menu");
            _statusView.SetProgress(1f);

            _view.Bind(new MenuUIViewModel(_restartSignal));
            _view.Initialize();

            try
            {
                await _restartSignal.WaitAsync(ct);
            }
            catch (OperationCanceledException) when (ct.IsCancellationRequested)
            {
                _view.Release();
                throw;
            }
        }

        public UniTask ExitAsync(CancellationToken ct)
        {
            _view.Release();
            return UniTask.CompletedTask;
        }
    }
}
