64 lines
2.2 KiB
C#
64 lines
2.2 KiB
C#
using AspShogiSockets.Extensions;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
using System.Linq;
|
|
using System.Net.WebSockets;
|
|
using System.Threading.Tasks;
|
|
using Websockets.Managers.Utility;
|
|
using Websockets.Repositories;
|
|
using Websockets.ServiceModels.Messages;
|
|
using Websockets.ServiceModels.Types;
|
|
|
|
namespace Websockets.Managers.ClientActionHandlers
|
|
{
|
|
public class LoadGameHandler : IActionHandler
|
|
{
|
|
private readonly ILogger<LoadGameHandler> logger;
|
|
private readonly IGameboardRepository gameboardRepository;
|
|
private readonly ISocketCommunicationManager communicationManager;
|
|
|
|
public LoadGameHandler(
|
|
ILogger<LoadGameHandler> logger,
|
|
ISocketCommunicationManager communicationManager,
|
|
IGameboardRepository gameboardRepository)
|
|
{
|
|
this.logger = logger;
|
|
this.gameboardRepository = gameboardRepository;
|
|
this.communicationManager = communicationManager;
|
|
}
|
|
|
|
public async Task Handle(WebSocket socket, string json, string userName)
|
|
{
|
|
logger.LogInformation("Socket Request \n{0}\n", json);
|
|
var request = JsonConvert.DeserializeObject<LoadGameRequest>(json);
|
|
var response = new LoadGameResponse(ClientAction.LoadGame);
|
|
var getGameResponse = await gameboardRepository.GetGame(request.GameName);
|
|
var getMovesResponse = await gameboardRepository.GetMoves(request.GameName);
|
|
|
|
if (getGameResponse == null || getMovesResponse == null)
|
|
{
|
|
response.Error = $"Could not find game.";
|
|
}
|
|
else
|
|
{
|
|
var session = getGameResponse.Session;
|
|
response.Game = new Game
|
|
{
|
|
GameName = session.Name,
|
|
Players = new[] { session.Player1, session.Player2 }
|
|
};
|
|
|
|
response.Moves = userName.Equals(session.Player1)
|
|
? getMovesResponse.Moves.Select(_ => Mapper.Map(_))
|
|
: getMovesResponse.Moves.Select(_ => Move.ConvertPerspective(Mapper.Map(_)));
|
|
|
|
communicationManager.SubscribeToGame(socket, session.Name, userName);
|
|
}
|
|
|
|
var serialized = JsonConvert.SerializeObject(response);
|
|
logger.LogInformation("Socket Response \n{0}\n", serialized);
|
|
await socket.SendTextAsync(serialized);
|
|
}
|
|
}
|
|
}
|