Files
Shogi/Gameboard.ShogiUI.Sockets/Repositories/RepositoryManagers/GameboardRepositoryManager.cs

64 lines
1.8 KiB
C#

using Gameboard.Shogi.Api.ServiceModels.Messages;
using System;
using System.Threading.Tasks;
namespace Gameboard.ShogiUI.Sockets.Repositories.RepositoryManagers
{
public interface IGameboardRepositoryManager
{
Task<string> CreateGuestUser();
Task<bool> IsPlayer1(string sessionName, string playerName);
bool IsGuest(string playerName);
}
public class GameboardRepositoryManager : IGameboardRepositoryManager
{
private const int MaxTries = 3;
private const string GuestPrefix = "Guest-";
private readonly IGameboardRepository repository;
public GameboardRepositoryManager(IGameboardRepository repository)
{
this.repository = repository;
}
public async Task<string> CreateGuestUser()
{
var count = 0;
while (count < MaxTries)
{
count++;
var clientId = $"Guest-{Guid.NewGuid()}";
var request = new PostPlayer
{
PlayerName = clientId
};
var response = await repository.PostPlayer(request);
if (response.IsSuccessStatusCode)
{
return clientId;
}
}
throw new OperationCanceledException($"Failed to create guest user after {MaxTries} tries.");
}
public async Task<bool> IsPlayer1(string sessionName, string playerName)
{
var session = await repository.GetGame(sessionName);
return session?.Session.Player1 == playerName;
}
public async Task<string> CreateJoinCode(string sessionName, string playerName)
{
var getGameResponse = await repository.GetGame(sessionName);
if (playerName == getGameResponse?.Session.Player1)
{
return (await repository.PostJoinCode(sessionName, playerName)).JoinCode;
}
return null;
}
public bool IsGuest(string playerName) => playerName.StartsWith(GuestPrefix);
}
}