using Gameboard.Shogi.Api.ServiceModels.Messages; using Gameboard.ShogiUI.Sockets.Extensions; 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.Net.WebSockets; using System.Threading.Tasks; namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers { public class CreateGameHandler : IActionHandler { private readonly ILogger logger; private readonly IGameboardRepository repository; private readonly ISocketCommunicationManager communicationManager; public CreateGameHandler( ILogger 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(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); } } } }