You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
League-of-Legends_Project/EntityFramework_LoL/Sources/ApiLib/ChampionsManager.cs

581 lines
23 KiB

using DTO;
using Model;
using Shared;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Xml.Linq;
using ApiMappeur;
namespace ApiLib
{
public partial class ApiManager
{
public class ChampionsManager : IChampionsManager
{
private readonly ApiManager parent;
public ChampionsManager(ApiManager parent)
=> this.parent = parent;
private const string urlChampion = "/champions";
public async Task<Champion?> AddItem(Champion? item)
{
try
{
if (item == null) throw new ArgumentNullException("Champions is null cannot add empty");
var response = await parent.HttpClient.PostAsJsonAsync(urlChampion, item.toFullDTO());
if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Created)// mayby changer to check the status code is more secure i think
{
Champion newChampion = await response.Content.ReadFromJsonAsync<Champion>();
Console.WriteLine("Champion {0} inserted", newChampion.Name);
return newChampion;
}
else
{
// Log the error status code and reason phrase
Console.WriteLine($"Failed to add item. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
// Log the error message from the HttpClient exception
Console.WriteLine($"Failed to add item. {ex.Message}");
return null;
}
catch (JsonException ex)
{
// Log the error message from the JSON serialization exception
Console.WriteLine($"Failed to add item. Error while serializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
// Log any other exceptions that may occur
Console.WriteLine($"Failed to add item. {ex.Message}");
return null;
}
}
public async Task<bool> DeleteItem(Champion? item)
{
try
{
if (item == null) throw new ArgumentNullException("Champions is null cannot add empty");
HttpResponseMessage response = await parent.HttpClient.DeleteAsync($"champions/{item.Name}");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Champion {0} deleted", item.Name);
return true;
}
else
{
Console.WriteLine($"Failed to delete item. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return false;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to delete item. {ex.Message}");
return false;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to delete item. {ex.Message}");
return false;
}
}
public async Task<IEnumerable<Champion?>> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
// should use Page request Object but to show that the api is rest
string queryString = $"?index={index}&count={count}";
if (!string.IsNullOrEmpty(orderingPropertyName))
{
queryString += $"&orderBy={orderingPropertyName}";
if (descending)
{
queryString += "&descending=true";
}
}
var response = await parent.HttpClient.GetAsync($"{urlChampion}{queryString}");
if (response.IsSuccessStatusCode)
{
IEnumerable<ChampionDTO?> champions = await response.Content.ReadFromJsonAsync<IEnumerable<ChampionDTO?>>();
Console.WriteLine(champions);
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
}
else
{
Console.WriteLine($"Failed to retrieve Champions. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve Champions. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve Champions. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve Champions. {ex.Message}");
return null;
}
}
public async Task<IEnumerable<Champion?>> GetItemsByCharacteristic(string charName, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
HttpResponseMessage response = await parent.HttpClient.GetAsync($"{urlChampion}/characteristic/{charName}?index={index}&count={count}&orderingPropertyName={orderingPropertyName}&descending={descending}");
if (response.IsSuccessStatusCode)
{
List<ChampionDTO?> champions = await response.Content.ReadFromJsonAsync<List<ChampionDTO>>();
Console.WriteLine($"Retrieved {champions.Count} champions with characteristic {charName}");
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
}
else
{
Console.WriteLine($"Failed to retrieve champions with characteristic {charName}. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve champions with characteristic {charName}. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve champions with characteristic {charName}. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve champions with characteristic {charName}. {ex.Message}");
return null;
}
}
public async Task<IEnumerable<Champion?>> GetItemsByClass(ChampionClass championClass, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
var queryString = new StringBuilder();
queryString.Append($"class={championClass}");
queryString.Append($"&Index={index}");
queryString.Append($"&Count={count}");
if (!string.IsNullOrEmpty(orderingPropertyName))
{
queryString.Append($"&OrderingPropertyName={orderingPropertyName}");
queryString.Append($"&Descending={descending}");
}
var uri = new UriBuilder(urlChampion)
{
Query = queryString.ToString()
}.Uri;
try
{
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var champions = await response.Content.ReadFromJsonAsync<IEnumerable<ChampionDTO?>>();
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
}
else
{
Console.WriteLine($"Failed to retrieve items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve items. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
}
public async Task<IEnumerable<Champion?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
/* string queryString = $"?name={substring}&index={index}&count={count}";
if (!string.IsNullOrEmpty(orderingPropertyName))
{
queryString += $"&orderBy={orderingPropertyName}";
if (descending)
{
queryString += "&descending=true";
}
}*/
Uri uri = new Uri($"{urlChampion}/{substring}");
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
IEnumerable<ChampionDTO> champions = await response.Content.ReadFromJsonAsync<IEnumerable<ChampionDTO>>();
Console.WriteLine(champions);
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
Console.WriteLine($"Found {res.Count()} champions that match the substring '{substring}'");
return res;
}
else
{
Console.WriteLine($"Failed to retrieve items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve items. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
}
public async Task<IEnumerable<Champion?>> GetItemsByRunePage(RunePage? runePage, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
string queryString = $"?index={index}&count={count}";
if (!string.IsNullOrEmpty(orderingPropertyName))
{
queryString += $"&orderBy={orderingPropertyName}";
if (descending)
{
queryString += "&descending=true";
}
}
if (runePage != null)
{
string runePageQueryString = string.Join("&", runePage.Runes
.Where(kv => kv.Value != null)
.Select(kv => $"{kv.Key}={kv.Value.Name}"));
if (!string.IsNullOrEmpty(runePageQueryString))
{
queryString += $"&{runePageQueryString}";
}
}
Uri uri = new Uri($"{urlChampion}/runePage{queryString}");
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
IEnumerable<Champion> champions = await response.Content.ReadFromJsonAsync<IEnumerable<Champion>>();
Console.WriteLine($"Found {champions.Count()} champions that match the Rune Page");
return champions;
}
else
{
Console.WriteLine($"Failed to retrieve items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve items. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
}
public Task<IEnumerable<Champion?>> GetItemsBySkill(Skill? skill, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
throw new NotImplementedException();
}
public Task<IEnumerable<Champion?>> GetItemsBySkill(string skill, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
throw new NotImplementedException();
}
public async Task<int> GetNbItems()
{
int count = 0;
try
{
var response = await parent.HttpClient.GetAsync($"{urlChampion}/count");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
count = int.Parse(responseBody);
}
}
catch (Exception ex)
{
// not sure about the -1 maybe sould juste log info
Console.WriteLine($"An error occurred while fetching the number of Champions: {ex.Message}");
return -1;
}
return count;
}
public async Task<int> GetNbItemsByCharacteristic(string charName)
{
int count = 0;
try
{
var response = await parent.HttpClient.GetAsync($"{urlChampion}/count/characteristic/{charName}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
if (!int.TryParse(responseBody, out count))
{
Console.WriteLine($"Error parsing response body {responseBody} to int");
return -1;
}
}
else
{
Console.WriteLine($"Error getting number of items by characteristic");
return -1;
}
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Error getting number of items by characteristic {charName}: {ex.Message}");
return -1;
}
return count;
}
public async Task<int> GetNbItemsByClass(ChampionClass championClass)
{
int count = 0;
try
{
var response = await parent.HttpClient.GetAsync($"{urlChampion}/count/class/{championClass}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
if (!int.TryParse(responseBody, out count))
{
Console.WriteLine($"Error parsing response body {responseBody} to int");
return -1;
}
}
else
{
Console.WriteLine($"Error getting number of items by class");
return -1;
}
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Error getting number of items by class {championClass}: {ex.Message}");
return -1;
}
return count;
}
public async Task<int> GetNbItemsByName(string substring)
{
int count = 0;
try
{
var response = await parent.HttpClient.GetAsync($"champions/count/name/{substring}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
if (!int.TryParse(responseBody, out count))
{
Console.WriteLine($"Error parsing response body {responseBody} to int");
return -1;
}
}
else
{
Console.WriteLine($"Error getting number of items by name");
return -1;
}
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Error getting number of items by name {substring}: {ex.Message}");
return -1;
}
return count;
}
public async Task<int> GetNbItemsByRunePage(RunePage? runePage)
{
int count = 0;
try
{
string requestUri = $"{urlChampion}/count/runePage";
if (runePage != null)
{
string runePageQueryString = string.Join("&", runePage.Runes
.Where(kv => kv.Value != null)
.Select(kv => $"{kv.Key}={kv.Value.Name}"));
if (!string.IsNullOrEmpty(runePageQueryString))
{
requestUri += "?runePage=" + Uri.EscapeDataString(runePageQueryString);
}
}
var response = await parent.HttpClient.GetAsync(requestUri);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
if (!int.TryParse(responseBody, out count))
{
Console.WriteLine($"Error parsing response body {responseBody} to int");
return -1;
}
}
else
{
Console.WriteLine($"Error getting number of items by rune page");
return -1;
}
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Error getting number of items by rune page: {ex.Message}");
return -1;
}
return count;
}
public Task<int> GetNbItemsBySkill(Skill? skill)
{
throw new NotImplementedException();
}
public Task<int> GetNbItemsBySkill(string skill)
{
throw new NotImplementedException();
}
public async Task<Champion?> UpdateItem(Champion? oldItem, Champion? newItem)
{
if (oldItem == null || newItem == null || oldItem.Name != newItem.Name)
{
Console.WriteLine("Error: oldItem or newItem is null");
return null;
}
try
{
var response = await parent.HttpClient.PutAsJsonAsync($"{urlChampion}/{oldItem.Name}", newItem);
if (response.IsSuccessStatusCode)
{
var updatedChampion = await response.Content.ReadFromJsonAsync<Champion>();
return updatedChampion;
}
else
{
Console.WriteLine($"Error updating champion {oldItem.Name}");
return null;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error updating champion {oldItem.Name}: {ex.Message}");
return null;
}
}
}
}
}