using Minesweeper.Commands;
using Minesweeper.Config;
using Minesweeper.Core;
using Minesweeper.Presentation.Views;

namespace Minesweeper.Presentation.Presenters
{
    public sealed class MainMenuPresenter : IPresenter
    {
        private readonly IGameCommandDispatcher commandDispatcher;
        private readonly MinesweeperGameConfig config;
        private readonly IGameSettingsService settingsService;
        private readonly IGameStateService gameStateService;
        private readonly IMainMenuView view;

        public MainMenuPresenter(IGameCommandDispatcher commandDispatcher, MinesweeperGameConfig config, IGameSettingsService settingsService, IGameStateService gameStateService, IMainMenuView view = null)
        {
            this.commandDispatcher = commandDispatcher;
            this.config = config;
            this.settingsService = settingsService;
            this.gameStateService = gameStateService;
            this.view = view;
        }

        public void Initialize()
        {
            if (view != null)
            {
                view.StartClicked += OnStartClicked;
                view.SizeChanged += OnSizeChanged;
                gameStateService.StateChanged += OnStateChanged;
                RefreshMenuValues(settingsService.Current);
                OnStateChanged(gameStateService.Current);
            }
        }

        public void Dispose()
        {
            if (view != null)
            {
                view.StartClicked -= OnStartClicked;
                view.SizeChanged -= OnSizeChanged;
                gameStateService.StateChanged -= OnStateChanged;
            }
        }

        private void OnStartClicked()
        {
            settingsService.ApplyAndSaveIfChanged(view.SelectedSettings);
            commandDispatcher.Dispatch(new StartGameCommand());
        }

        private void OnSizeChanged()
        {
            var selected = settingsService.Clamp(view.SelectedSettings);
            var maxMines = settingsService.GetMaxMines(selected.SizeX, selected.SizeY);
            view.ConfigureMines(1, maxMines, selected.MinesCount);
        }

        private void OnStateChanged(GameState state)
        {
            if (state == GameState.FieldSelection)
            {
                RefreshMenuValues(settingsService.Current);
                view.Show();
            }
            else
            {
                view.Hide();
            }
        }

        private void RefreshMenuValues(GameSettingsValue settings)
        {
            var clamped = settingsService.Clamp(settings);
            view.ConfigureSizeX(config.MinSizeX, config.MaxSizeX, clamped.SizeX);
            view.ConfigureSizeY(config.MinSizeY, config.MaxSizeY, clamped.SizeY);
            view.ConfigureMines(1, settingsService.GetMaxMines(clamped.SizeX, clamped.SizeY), clamped.MinesCount);
        }
    }
}
