using FastGithub.Configuration;
using FastGithub.DomainResolve;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace FastGithub.Http
{
    /// 
    /// 表示http客户端
    /// 
    public class HttpClient : HttpMessageInvoker
    {
        /// 
        /// 插入的UserAgent标记
        /// 
        private readonly static ProductInfoHeaderValue userAgent = new(new ProductHeaderValue(nameof(FastGithub), "1.0"));
        /// 
        /// http客户端
        /// 
        /// 
        /// 
        public HttpClient(DomainConfig domainConfig, IDomainResolver domainResolver)
            : this(new HttpClientHandler(domainConfig, domainResolver), disposeHandler: true)
        {
        }
        /// 
        /// http客户端
        ///  
        /// 
        /// 
        public HttpClient(HttpMessageHandler handler, bool disposeHandler)
            : base(handler, disposeHandler)
        {
        }
        /// 
        /// 发送请求
        /// 
        /// 
        /// 
        /// 
        public override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Headers.UserAgent.Contains(userAgent))
            {
                throw new FastGithubException($"由于{request.RequestUri}实际指向了{nameof(FastGithub)}自身,{nameof(FastGithub)}已中断本次转发");
            }
            request.Headers.UserAgent.Add(userAgent);
            var response = await base.SendAsync(request, cancellationToken);
            response.Headers.Server.TryParseAdd(nameof(FastGithub));
            return response;
        }
    }
}