using FastGithub.Configuration;
using FastGithub.DomainResolve;
using System;
using System.Collections.Concurrent;
namespace FastGithub.Http
{
    /// 
    /// HttpClient工厂
    /// 
    sealed class HttpClientFactory : IHttpClientFactory
    {
        private readonly IDomainResolver domainResolver;
        /// 
        /// 首次生命周期
        /// 
        private readonly TimeSpan firstLiftTime = TimeSpan.FromSeconds(10d);
        /// 
        /// 非首次生命周期
        /// 
        private readonly TimeSpan nextLifeTime = TimeSpan.FromMinutes(1d);
        /// 
        /// LifetimeHttpHandler清理器
        /// 
        private readonly LifetimeHttpHandlerCleaner httpHandlerCleaner = new();
        /// 
        /// LazyOf(LifetimeHttpHandler)缓存
        /// 
        private readonly ConcurrentDictionary> httpHandlerLazyCache = new();
        /// 
        /// HttpClient工厂
        /// 
        /// 
        public HttpClientFactory(IDomainResolver domainResolver)
        {
            this.domainResolver = domainResolver;
        }
        /// 
        /// 创建httpClient
        /// 
        /// 
        /// 
        public HttpClient CreateHttpClient(DomainConfig domainConfig)
        {
            var lifetimeHttpHandlerLazy = this.httpHandlerLazyCache.GetOrAdd(domainConfig, CreateLifetimeHttpHandlerLazy);
            var lifetimeHttpHandler = lifetimeHttpHandlerLazy.Value;
            return new HttpClient(lifetimeHttpHandler, disposeHandler: false);
            Lazy CreateLifetimeHttpHandlerLazy(DomainConfig domainConfig)
            {
                return new Lazy(() => this.CreateLifetimeHttpHandler(domainConfig, this.firstLiftTime), true);
            }
        }
        /// 
        /// 当有httpHandler失效时
        /// 
        /// httpHandler
        private void OnLifetimeHttpHandlerDeactivate(LifetimeHttpHandler lifetimeHttpHandler)
        {
            var domainConfig = lifetimeHttpHandler.DomainConfig;
            this.httpHandlerLazyCache[domainConfig] = CreateLifetimeHttpHandlerLazy(domainConfig);
            this.httpHandlerCleaner.Add(lifetimeHttpHandler);
            Lazy CreateLifetimeHttpHandlerLazy(DomainConfig domainConfig)
            {
                return new Lazy(() => this.CreateLifetimeHttpHandler(domainConfig, this.nextLifeTime), true);
            }
        }
        /// 
        /// 创建LifetimeHttpHandler
        /// 
        /// 
        /// 
        /// 
        private LifetimeHttpHandler CreateLifetimeHttpHandler(DomainConfig domainConfig, TimeSpan lifeTime)
        {
            var httpClientHandler = new HttpClientHandler(domainConfig, this.domainResolver);
            return new LifetimeHttpHandler(httpClientHandler, lifeTime, this.OnLifetimeHttpHandlerDeactivate);
        }
    }
}