using Gameboard.Shogi.Api.ServiceModels.Messages; using Gameboard.ShogiUI.Sockets.Extensions; using Gameboard.ShogiUI.Sockets.Managers.Utility; using Gameboard.ShogiUI.Sockets.Repositories; using Service = Gameboard.ShogiUI.Sockets.ServiceModels.Socket; using Newtonsoft.Json; using System.Net.WebSockets; using System.Threading.Tasks; using Gameboard.ShogiUI.Sockets.Models; namespace Gameboard.ShogiUI.Sockets.Managers.ClientActionHandlers { public class MoveHandler : IActionHandler { private readonly IGameboardRepository gameboardRepository; private readonly ISocketCommunicationManager communicationManager; public MoveHandler( ISocketCommunicationManager communicationManager, IGameboardRepository gameboardRepository) { this.gameboardRepository = gameboardRepository; this.communicationManager = communicationManager; } public async Task Handle(WebSocket socket, string json, string userName) { var request = JsonConvert.DeserializeObject(json); // Basic move validation if (request.Move.To.Equals(request.Move.From)) { var serialized = JsonConvert.SerializeObject( new Service.Messages.ErrorResponse(Service.Types.ClientAction.Move) { Error = "Error: moving piece from tile to the same tile." }); await socket.SendTextAsync(serialized); return; } var moveModel = new Move(request.Move); var session = (await gameboardRepository.GetGame(request.GameName)).Session; await gameboardRepository.PostMove(request.GameName, new PostMove(Mapper.Map(moveModel))); var response = new Service.Messages.MoveResponse(Service.Types.ClientAction.Move) { GameName = request.GameName, PlayerName = userName, Move = moveModel.ToServiceModel() }; await communicationManager.BroadcastToGame(session.Name, response); } } }