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

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

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

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

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

        private void OnStartClicked()
        {
            commandDispatcher.Dispatch(new StartGameCommand());
        }

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