using BlazorLottoPicker.Data.Model;
using Newtonsoft.Json;

namespace BlazorLottoPicker.Data.Services
{
    public class HistoryService
    {
        private HttpClient _httpClient;
        private string url = "http://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=";

        public HistoryService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        // Read
        public async Task<HistoryResult> GetHistoryAsync(int round)
        {
            var result = await _httpClient.GetAsync($"{url}{round}");
            if (!result.IsSuccessStatusCode)
                throw new Exception("Fail to get history");

            var resultContent = await result.Content.ReadAsStringAsync();
            HistoryResult resultObject = JsonConvert.DeserializeObject<HistoryResult>(resultContent);

            return resultObject;
        }

        // Read bulk list
        public async Task<List<HistoryResult>> GetHistoryListAsync(int start, int end)
        {
            List<HistoryResult> resultList = new List<HistoryResult>();
            for (int i = start; i <= end; i++)
            {
                var result = await _httpClient.GetAsync($"{url}{i}");
                if (!result.IsSuccessStatusCode)
                    continue;

                var resultContent = await result.Content.ReadAsStringAsync();
                HistoryResult resultObject = JsonConvert.DeserializeObject<HistoryResult>(resultContent);

                resultList.Add(resultObject);
            }

            return resultList;
        }
    }
}
