67 lines
2.6 KiB
C#
67 lines
2.6 KiB
C#
using Gameboard.ShogiUI.BoardState;
|
|
using Gameboard.ShogiUI.Sockets.Repositories;
|
|
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Messages;
|
|
using Gameboard.ShogiUI.Sockets.ServiceModels.Socket.Types;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
|
|
{
|
|
/// <summary>
|
|
/// Subscribes a user to messages for a session and loads that session into the BoardManager for playing.
|
|
/// </summary>
|
|
public class LoadGameHandler : IActionHandler
|
|
{
|
|
private readonly ILogger<LoadGameHandler> logger;
|
|
private readonly IGameboardRepository gameboardRepository;
|
|
private readonly ISocketCommunicationManager communicationManager;
|
|
private readonly IBoardManager boardManager;
|
|
|
|
public LoadGameHandler(
|
|
ILogger<LoadGameHandler> logger,
|
|
ISocketCommunicationManager communicationManager,
|
|
IGameboardRepository gameboardRepository,
|
|
IBoardManager boardManager)
|
|
{
|
|
this.logger = logger;
|
|
this.gameboardRepository = gameboardRepository;
|
|
this.communicationManager = communicationManager;
|
|
this.boardManager = boardManager;
|
|
}
|
|
|
|
public async Task Handle(string json, string userName)
|
|
{
|
|
var request = JsonConvert.DeserializeObject<LoadGameRequest>(json);
|
|
var gameTask = gameboardRepository.GetGame(request.GameName);
|
|
var moveTask = gameboardRepository.GetMoves(request.GameName);
|
|
|
|
var getGameResponse = await gameTask;
|
|
var getMovesResponse = await moveTask;
|
|
if (getGameResponse == null || getMovesResponse == null)
|
|
{
|
|
logger.LogWarning("{action} - {user} was unable to load session named {session}.", ClientAction.LoadGame, userName, request.GameName);
|
|
var response = new LoadGameResponse(ClientAction.LoadGame) { Error = "Game not found." };
|
|
await communicationManager.BroadcastToPlayers(response, userName);
|
|
}
|
|
else
|
|
{
|
|
var sessionModel = new Models.Session(getGameResponse.Session);
|
|
var moveModels = getMovesResponse.Moves.Select(_ => new Models.Move(_)).ToList();
|
|
|
|
communicationManager.SubscribeToGame(sessionModel, userName);
|
|
var boardMoves = moveModels.Select(_ => _.ToBoardModel()).ToList();
|
|
boardManager.Add(getGameResponse.Session.Name, new ShogiBoard(boardMoves));
|
|
|
|
var response = new LoadGameResponse(ClientAction.LoadGame)
|
|
{
|
|
Game = sessionModel.ToServiceModel(),
|
|
Moves = moveModels.Select(_ => _.ToServiceModel()).ToList(),
|
|
};
|
|
await communicationManager.BroadcastToPlayers(response, userName);
|
|
}
|
|
}
|
|
}
|
|
}
|