using CH.CryptoStats.Abstractions; using Microsoft.Extensions.Configuration; using System.Net.Http.Json; using System.Text.Json; using CH.Energy.Abstractions.Enum; 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 quoteData = coinMarketCapEntity.Quote.CAD ?? coinMarketCapEntity.Quote.USD; var cryptoStats = new Abstractions.CryptoStats { Name = coinMarketCapEntity.Name, Symbol = coinMarketCapEntity.Symbol, MaxSupply = coinMarketCapEntity.MaxSupply, CirculatingSupply = coinMarketCapEntity.CirculatingSupply, TotalSupply = coinMarketCapEntity.TotalSupply, Currency = (Currency)System.Enum.Parse(typeof(Currency), currency.ToUpper()), UpdatedAt = DateTime.Parse(coinMarketCapEntity.LastUpdated), Price = quoteData.Price, Volume24H = quoteData.Volume24H, VolumeChange24H = quoteData.VolumeChange24H, MarketCap = quoteData.MarketCap, MarketCapDominance = quoteData.MarketCapDominance, FullyDilutedMarketCap = quoteData.FullyDilutedMarketCap }; return Task.FromResult(cryptoStats); } }