using Minesweeper.Commands;
using Minesweeper.Config;
using Minesweeper.Core;
using UnityEngine.InputSystem;
using VContainer.Unity;

namespace Minesweeper.Infrastructure
{
    public sealed class RestartKeyInputService : ITickable
    {
        private readonly IGameCommandDispatcher commandDispatcher;
        private readonly MinesweeperGameConfig config;
        private readonly IGameStateService gameStateService;

        public RestartKeyInputService(IGameCommandDispatcher commandDispatcher, MinesweeperGameConfig config, IGameStateService gameStateService)
        {
            this.commandDispatcher = commandDispatcher;
            this.config = config;
            this.gameStateService = gameStateService;
        }

        public void Tick()
        {
            var keyboard = Keyboard.current;
            if (keyboard == null || !IsRestartPressed(keyboard))
            {
                return;
            }

            if (gameStateService.Current == GameState.FieldSelection)
            {
                commandDispatcher.Dispatch(new StartGameCommand());
            }
            else
            {
                commandDispatcher.Dispatch(new RestartCommand());
            }
        }

        private bool IsRestartPressed(Keyboard keyboard)
        {
            if (config.RestartKey == UnityEngine.KeyCode.R)
            {
                return keyboard.rKey.wasPressedThisFrame;
            }

            return false;
        }
    }
}
