using Shogi.Contracts.Api; using Shogi.Contracts.Types; using System.Net; using System.Net.Http.Json; using System.Reflection.Metadata.Ecma335; using System.Text.Json; namespace Shogi.UI.Shared; public class ShogiApi(HttpClient httpClient) { private readonly JsonSerializerOptions serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web); public async Task Register(string email, string password) { var response = await httpClient.PostAsJsonAsync(Relative("register"), new { email, password }); response.EnsureSuccessStatusCode(); } public async Task LoginEventArgs(string email, string password) { var response = await httpClient.PostAsJsonAsync("login?useCookies=true", new { email, password }); response.EnsureSuccessStatusCode(); } public async Task Logout() { var response = await httpClient.PutAsync(Relative("User/GuestLogout"), null); response.EnsureSuccessStatusCode(); } public async Task GetSession(string name) { var response = await httpClient.GetAsync(Relative($"Sessions/{name}")); if (response.IsSuccessStatusCode) { return (await response.Content.ReadFromJsonAsync(this.serializerOptions)); } return null; } public async Task GetAllSessionsMetadata() { var response = await httpClient.GetAsync(Relative("Sessions")); if (response.IsSuccessStatusCode) { return (await response.Content.ReadFromJsonAsync(this.serializerOptions))!; } return []; } /// /// Returns false if the move was not accepted by the server. /// public async Task Move(string sessionName, MovePieceCommand command) { var response = await httpClient.PatchAsync(Relative($"Sessions/{sessionName}/Move"), JsonContent.Create(command)); return response.IsSuccessStatusCode; } public async Task PostSession() { var response = await httpClient.PostAsync(Relative("Sessions"), null); var sessionId = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null; return sessionId; } public Task PatchJoinGame(string name) { return httpClient.PatchAsync(Relative($"Sessions/{name}/Join"), null); } public Task DeleteSession(Guid sessionId) { return httpClient.DeleteAsync(Relative($"Sessions/{sessionId}")); } private static Uri Relative(string path) => new(path, UriKind.Relative); }