using JobsJobsJobs.Shared;
using JobsJobsJobs.Shared.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;
namespace JobsJobsJobs.Client
{
///
/// Functions used to access the API
///
public static class ServerApi
{
///
/// Create an API URL
///
/// The URL to append to the API base URL
/// The full URL to be used in HTTP requests
private static string ApiUrl(string url) => $"/api/{url}";
///
/// Create an HTTP request with an authorization header
///
/// The current application state
/// The URL for the request (will be appended to the API root)
/// The request method (optional, defaults to GET)
/// A request with the header attached, ready for further manipulation
private static HttpRequestMessage WithHeader(AppState state, string url, HttpMethod? method = null)
{
var req = new HttpRequestMessage(method ?? HttpMethod.Get, ApiUrl(url));
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", state.Jwt);
return req;
}
///
/// Log on a user with the authorization code received from No Agenda Social
///
/// The HTTP client to use for server communication
/// The authorization code received from NAS
/// The log on details if successful, an error if not
public static async Task> LogOn(HttpClient http, string authCode)
{
try
{
var logOn = await http.GetFromJsonAsync(ApiUrl($"citizen/log-on/{authCode}"));
if (logOn == null) {
return Result.AsError(
"Unable to log on with No Agenda Social. This should never happen; contact @danieljsummers");
}
return Result.AsOk(logOn);
}
catch (HttpRequestException ex)
{
return Result.AsError($"Unable to log on with No Agenda Social: {ex.Message}");
}
}
///
/// Retrieve a citizen's profile
///
/// The HTTP client to use for server communication
/// The current application state
/// The citizen's profile, null if it is not found, or an error message if one occurs
public static async Task> RetrieveProfile(HttpClient http, AppState state)
{
var req = WithHeader(state, "profile/");
var res = await http.SendAsync(req);
return true switch
{
_ when res.StatusCode == HttpStatusCode.NoContent => Result.AsOk(null),
_ when res.IsSuccessStatusCode => Result.AsOk(await res.Content.ReadFromJsonAsync()),
_ => Result.AsError(await res.Content.ReadAsStringAsync()),
};
}
}
}