using Minesweeper.Commands;
using Minesweeper.Presentation.ReadModels;
using Minesweeper.Presentation.Views;

namespace Minesweeper.Presentation.Presenters
{
    public sealed class GamePresenter : IPresenter
    {
        private readonly IGameCommandDispatcher commandDispatcher;
        private readonly IGameReadModel readModel;
        private readonly IGameView view;

        public GamePresenter(IGameCommandDispatcher commandDispatcher, IGameReadModel readModel, IGameView view = null)
        {
            this.commandDispatcher = commandDispatcher;
            this.readModel = readModel;
            this.view = view;
        }

        public void Initialize()
        {
            _ = readModel.State;

            if (view != null)
            {
                view.RestartRequested += OnRestartRequested;
                view.GoToMenuRequested += OnGoToMenuRequested;
            }
        }

        public void Dispose()
        {
            if (view != null)
            {
                view.RestartRequested -= OnRestartRequested;
                view.GoToMenuRequested -= OnGoToMenuRequested;
            }
        }

        private void OnRestartRequested()
        {
            commandDispatcher.Dispatch(new RestartCommand());
        }

        private void OnGoToMenuRequested()
        {
            commandDispatcher.Dispatch(new GoToMenuCommand());
        }
    }
}
