Files
Shogi/Gameboard.ShogiUI.Sockets/Managers/ClientActionHandlers/CreateGameHandler.cs
Lucas Morgan 2c8e692d38 Upgrade to .net 5
Address breaking changes from Shogi.API nuget
2021-01-23 18:11:19 -06:00

68 lines
2.1 KiB
C#

using AspShogiSockets.Extensions;
using Gameboard.Shogi.Api.ServiceModels.Messages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.WebSockets;
using System.Threading.Tasks;
using Websockets.Repositories;
using Websockets.ServiceModels.Messages;
using Websockets.ServiceModels.Types;
namespace Websockets.Managers.ClientActionHandlers
{
public class CreateGameHandler : IActionHandler
{
private readonly ILogger<CreateGameHandler> logger;
private readonly IGameboardRepository repository;
private readonly ISocketCommunicationManager communicationManager;
public CreateGameHandler(
ILogger<CreateGameHandler> logger,
ISocketCommunicationManager communicationManager,
IGameboardRepository repository)
{
this.logger = logger;
this.repository = repository;
this.communicationManager = communicationManager;
}
public async Task Handle(WebSocket socket, string json, string userName)
{
logger.LogInformation("Socket Request \n{0}\n", new[] { json });
var request = JsonConvert.DeserializeObject<CreateGameRequest>(json);
var postSessionResponse = await repository.PostSession(new PostSession
{
SessionName = request.GameName,
PlayerName = userName, // TODO : Investigate if needed by UI
IsPrivate = request.IsPrivate
});
var response = new CreateGameResponse(request.Action)
{
PlayerName = userName,
Game = new Game
{
GameName = postSessionResponse.SessionName,
Players = new string[] { userName }
}
};
if (string.IsNullOrWhiteSpace(postSessionResponse.SessionName))
{
response.Error = "Game already exists.";
}
var serialized = JsonConvert.SerializeObject(response);
logger.LogInformation("Socket Response \n{0}\n", new[] { serialized });
if (request.IsPrivate)
{
await socket.SendTextAsync(serialized);
}
else
{
await communicationManager.BroadcastToAll(serialized);
}
}
}
}