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 IGameboardRepository repository; private readonly ISocketCommunicationManager communicationManager; public CreateGameHandler( ISocketCommunicationManager communicationManager, IGameboardRepository repository) { this.repository = repository; this.communicationManager = communicationManager; } public async Task Handle(string json, string userName) { var request = JsonConvert.DeserializeObject(json); var sessionName = 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 = sessionName, Players = new[] { userName } } }; if (string.IsNullOrWhiteSpace(sessionName)) { response.Error = "Game already exists."; } if (request.IsPrivate) { await communicationManager.BroadcastToPlayers(response, userName); } else { await communicationManager.BroadcastToAll(response); } } } }