using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; using BlizzSharp.Data; using System.Collections.Generic; namespace BlizzSharp { public class BlizzSharpClient { private readonly Dictionary _itemLookup; private string _key; private HttpClient _http; private JsonSerializer _serializer; private long _latestTimeStamp; public AuctionResponse CurrentAuctionResponse {get;set;} public AuctionResponse PreviousAuctionResponse {get;set;} public BlizzSharpClient(string key) { _itemLookup = new Dictionary(); _serializer = new JsonSerializer(); _http = new HttpClient(); _http.BaseAddress = new Uri("https://eu.api.battle.net/wow/"); _http.DefaultRequestHeaders.Accept.Clear(); _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _key = key; _latestTimeStamp = -1; } //TODO: Exception handling public async Task GetAuctionsAsync(string realm, string locale) { HttpResponseMessage response = await _http.GetAsync($"auction/data/{realm}?locale={locale}&apikey={_key}"); if(response.IsSuccessStatusCode) { string auctionsLocatorResponse = await response.Content.ReadAsStringAsync(); AuctionLocator locator = JsonConvert.DeserializeObject(auctionsLocatorResponse).Locators[0]; if((locator.Timestamp > _latestTimeStamp) || CurrentAuctionResponse == null) { using(HttpClient auctionClient = new HttpClient()) { HttpResponseMessage auctionResponse = await auctionClient.GetAsync(locator.Url); if(auctionResponse.IsSuccessStatusCode) { string auctionsResponse = await auctionResponse.Content.ReadAsStringAsync(); PreviousAuctionResponse = CurrentAuctionResponse; CurrentAuctionResponse = JsonConvert.DeserializeObject(auctionsResponse); return CurrentAuctionResponse; } } } } return null; } public async Task GetItemInfoAsync(long itemId, string locale) { if(_itemLookup.ContainsKey(itemId)) return _itemLookup[itemId]; HttpResponseMessage response = await _http.GetAsync($"item/{itemId}?locale={locale}&apikey={_key}"); if(response.IsSuccessStatusCode) { string itemResponse = await response.Content.ReadAsStringAsync(); Item item = JsonConvert.DeserializeObject(itemResponse); _itemLookup[itemId] = item; return item; } return null; } } }