62 lines
2.3 KiB
C#
62 lines
2.3 KiB
C#
using Gameboard.ShogiUI.Sockets.Models;
|
|
using Gameboard.ShogiUI.Sockets.Repositories;
|
|
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
|
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
|
using Microsoft.Extensions.Logging;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
|
{
|
|
public interface ILoadGameHandler
|
|
{
|
|
Task Handle(LoadGameRequest request, string userName);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Subscribes a user to messages for a session and loads that session into the BoardManager for playing.
|
|
/// </summary>
|
|
public class LoadGameHandler : ILoadGameHandler
|
|
{
|
|
private readonly ILogger<LoadGameHandler> logger;
|
|
private readonly IGameboardRepository gameboardRepository;
|
|
private readonly ISocketConnectionManager communicationManager;
|
|
private readonly IActiveSessionManager boardManager;
|
|
|
|
public LoadGameHandler(
|
|
ILogger<LoadGameHandler> logger,
|
|
ISocketConnectionManager communicationManager,
|
|
IGameboardRepository gameboardRepository,
|
|
IActiveSessionManager boardManager)
|
|
{
|
|
this.logger = logger;
|
|
this.gameboardRepository = gameboardRepository;
|
|
this.communicationManager = communicationManager;
|
|
this.boardManager = boardManager;
|
|
}
|
|
|
|
public async Task Handle(LoadGameRequest request, string userName)
|
|
{
|
|
var sessionModel = await gameboardRepository.ReadSession(request.GameName);
|
|
if (sessionModel == null)
|
|
{
|
|
logger.LogWarning("{action} - {user} was unable to load session named {session}.", ClientAction.LoadGame, userName, request.GameName);
|
|
var error = new LoadGameResponse(ClientAction.LoadGame) { Error = "Game not found." };
|
|
await communicationManager.BroadcastToPlayers(error, userName);
|
|
return;
|
|
}
|
|
|
|
communicationManager.SubscribeToGame(sessionModel, userName);
|
|
boardManager.Add(sessionModel);
|
|
|
|
var response = new LoadGameResponse(ClientAction.LoadGame)
|
|
{
|
|
Game = new SessionMetadata(sessionModel).ToServiceModel(),
|
|
BoardState = sessionModel.Shogi.ToServiceModel(),
|
|
MoveHistory = sessionModel.Shogi.MoveHistory.Select(_ => _.ToServiceModel()).ToList()
|
|
};
|
|
await communicationManager.BroadcastToPlayers(response, userName);
|
|
}
|
|
}
|
|
}
|