using AyCode.Core.Enums;
using AyCode.Core.Loggers;
using AyCode.Entities;
using System.Net;
using System.Net.Http.Json;
using AyCode.Core.Helpers;

namespace AyCode.Services.Loggers;

public abstract class AcHttpClientLogItemWriter<TLogItem> : AcLogItemWriterBase<TLogItem>, IAcLogWriterClientBase where TLogItem : class, IAcLogItemClient
{
    protected string _url;
    protected HttpClient _httpClient;
    protected HttpClientHandler _httpClientHandler;

    protected AcHttpClientLogItemWriter(HttpClient httpClient, string url) : base(AppType.Web, LogLevel.Detail)
    {
        //_httpClient = httpClient;
        _url = url;
        Initialize(httpClient.BaseAddress, httpClient.DefaultRequestVersion, httpClient.DefaultVersionPolicy);
    }

    protected AcHttpClientLogItemWriter(string url, string? categoryName = null) : base(categoryName)
    {
        _url = url;
        Initialize(null, HttpVersion.Version20, HttpVersionPolicy.RequestVersionOrHigher);
    }

    protected AcHttpClientLogItemWriter(string url, AppType appType, LogLevel logLevel, string? categoryName = null) : base(appType, logLevel, categoryName)
    {
        _url = url;
        Initialize(null, HttpVersion.Version20, HttpVersionPolicy.RequestVersionOrHigher);
    }

    private void Initialize(Uri? baseAddress, Version defaultRequestVersion, HttpVersionPolicy defaultVersionPolicy)
    {
        _httpClientHandler = new HttpClientHandler();
        _httpClient = new HttpClient(_httpClientHandler, false);

        _httpClient.BaseAddress = baseAddress;
        _httpClient.DefaultRequestVersion = defaultRequestVersion;
        _httpClient.DefaultVersionPolicy = defaultVersionPolicy;
    }

    public override void Write(AppType appType, LogLevel logLevel, string? logText, string? callerMemberName, string? categoryName, string? errorType, string? exMessage)
        => WriteLogItem(CreateLogItem(DateTime.UtcNow, appType, Environment.CurrentManagedThreadId, logLevel, logText, callerMemberName, categoryName, errorType, exMessage));

    protected override void WriteLogItemCallback(TLogItem logItem)
    {
        //logItem.ThreadId = Environment.CurrentManagedThreadId;
        _httpClient.PostAsJsonAsync(_url, logItem).Forget();
    }

    //protected override void WriteLogItem(TLogItem logItem, Action? callback = null)
    //{
    //    //throw new NotImplementedException();

    //    base.WriteLogItem(logItem, () =>
    //    {
    //        //http.PostAsJson(url, Param);
    //        //_httpClient.Send()
    //    });
    //}

    //protected override void WriteLogItem(TLogItem logItem, Action<IEnumerable<TLogItem>>? callback = null)
    //{
    //    throw new NotImplementedException();

    //    base.WriteLogItem(logItem, logItems =>
    //    {
    //        //_httpClient.Send()
    //    });
    //}
}