Files
Shogi/Gameboard.ShogiUI.Sockets/Managers/ClientActionHandlers/CreateGameHandler.cs
2021-02-23 18:03:23 -06:00

65 lines
2.0 KiB
C#

using Gameboard.Shogi.Api.ServiceModels.Messages;
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.Threading.Tasks;
namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers
{
// TODO: This doesn't need to be a socket action.
// It can be an API route and still tell socket connections about the new session.
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(string json, string userName)
{
var request = JsonConvert.DeserializeObject<CreateGameRequest>(json);
var postSessionResponse = await repository.PostSession(new PostSession
{
SessionName = request.GameName,
PlayerName = userName,
IsPrivate = request.IsPrivate
});
var response = new CreateGameResponse(request.Action)
{
PlayerName = userName,
Game = new Game
{
GameName = postSessionResponse.SessionName,
Players = new[] { userName }
}
};
if (string.IsNullOrWhiteSpace(postSessionResponse.SessionName))
{
response.Error = "Game already exists.";
}
if (request.IsPrivate)
{
await communicationManager.BroadcastToPlayers(response, userName);
}
else
{
await communicationManager.BroadcastToAll(response);
}
}
}
}