using CH.CryptoStats.Abstractions; using Microsoft.Extensions.Configuration; using System.Net.Http.Json; using System.Text.Json; namespace CH.CryptoStats.CoinMarketCap; public class CoinMarketCapService(HttpClient httpClient, IConfiguration configuration) : ICryptoStats { public async Task GetCryptoStatsAsync(string cryptoName, string currency, CancellationToken cancellationToken) { var apiKey = configuration.GetValue("CoinMarketCap:ApiKey"); var apiUrl = configuration.GetValue("CoinMarketCap:ApiUrl"); var response = await httpClient.GetAsync($"{apiUrl}slug={cryptoName}&convert={currency}&CMC_PRO_API_KEY={apiKey}",cancellationToken); var jsonResponse = await response.Content.ReadFromJsonAsync(cancellationToken); return ParseCryptoStats(jsonResponse.Data["1"], currency, cancellationToken).Result; } private Task ParseCryptoStats(CoinMarketCapEntity coinMarketCapEntity, string currency, CancellationToken cancellationToken) { var cryptoStats = new Abstractions.CryptoStats { Name = coinMarketCapEntity.Name, Symbol = coinMarketCapEntity.Symbol, MaxSupply = coinMarketCapEntity.MaxSupply, CirculatingSupply = coinMarketCapEntity.CirculatingSupply, TotalSupply = coinMarketCapEntity.TotalSupply, Currency = currency.ToUpper(), UpdatedAt = DateTime.Parse(coinMarketCapEntity.LastUpdated), Price = coinMarketCapEntity.Quote.CAD == null ? coinMarketCapEntity.Quote.USD.Price : coinMarketCapEntity.Quote.CAD.Price, Volume24H = coinMarketCapEntity.Quote.CAD == null ? coinMarketCapEntity.Quote.USD.Volume24h : coinMarketCapEntity.Quote.CAD.Volume24h, VolumeChange24H = coinMarketCapEntity.Quote.CAD == null ? coinMarketCapEntity.Quote.USD.VolumeChange24h : coinMarketCapEntity.Quote.CAD.VolumeChange24h, MarketCap = coinMarketCapEntity.Quote.CAD == null ? coinMarketCapEntity.Quote.USD.MarketCap : coinMarketCapEntity.Quote.CAD.MarketCap, MarketCapDominance = coinMarketCapEntity.Quote.CAD == null ? coinMarketCapEntity.Quote.USD.MarketCapDominance : coinMarketCapEntity.Quote.CAD.MarketCapDominance, FullyDilutedMarketCap = coinMarketCapEntity.Quote.CAD == null ? coinMarketCapEntity.Quote.USD.FullyDilutedMarketCap : coinMarketCapEntity.Quote.CAD.FullyDilutedMarketCap }; return Task.FromResult(cryptoStats); } }