using System.Net.Http.Headers;
using Fast.Shared.Logic.FileService;
using Fast.Web.Models;
using Newtonsoft.Json;

namespace Fast.Web.Logic;

public class CmeDataMineApiClient
{
    private const string BaseListUrl = @"https://datamine.new.cmegroup.com/api/list_entitlements_files";
    private const string BaseDownloadUrl = @"https://datamine.new.cmegroup.com/cme/api/v2/download";
    private const string Username = @"api_SNGC1988";
    private const string Password = @"J4aN*QD9gmhGtmnYJJ*d@DDG";
    private AuthenticationHeaderValue AuthenticationHeader { get; set; }
    public readonly IWebHostEnvironment env;
    private readonly FileService fileService;

    public CmeDataMineApiClient(IWebHostEnvironment env, FileService fileService)
    {
        this.env = env;
        this.fileService = fileService;
        var authenticationString = $"{Username}:{Password}";
        var base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.ASCII.GetBytes(authenticationString));
        AuthenticationHeader = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
    }

    public async Task<DataMineListResponse> GetListResponseAsync()
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = AuthenticationHeader;

        var response = (await client.GetAsync(BaseListUrl)).EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<DataMineListResponse>(content) ?? throw new Exception("Deserialization failed");
    }

    public async Task<List<DataMineSettlementRecord>> GetSettlementDataAsync(string fid)
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = AuthenticationHeader;
        var downloadUrl = BaseDownloadUrl + $"?fid={fid}";
        var response = (await client.GetAsync(downloadUrl)).EnsureSuccessStatusCode();
        var content = await response.Content.ReadAsStringAsync();

        await fileService.WriteAllBytesAsync("CmePrices", fid + ".csv", Encoding.UTF8.GetBytes(content), useSharding: false);
        var records = GetRecordsFromFileText(content);
        return records;
    }

    internal static List<DataMineSettlementRecord> GetRecordsFromFileText(string textContent)
    {
        var records = new List<DataMineSettlementRecord>();
        var lines = textContent.Split('\n');

        //start at 1 since the first line is column headers
        for (int i = 1; i < lines.Length; i++)
        {
            var line = lines[i];
            if (string.IsNullOrWhiteSpace(line) || line.Length < 5)
                continue;

            var record = new DataMineSettlementRecord(line);
            records.Add(record);
        }

        return records;
    }
}
