using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace FastGithub.Scanner
{
    /// 
    /// 域名与ip关系工厂
    /// 
    [Service(ServiceLifetime.Singleton)]
    sealed class GithubLookupFacotry
    {
        private readonly IEnumerable providers;
        private readonly IOptionsMonitor options;
        private readonly ILogger logger;
        /// 
        /// 域名与ip关系工厂
        /// 
        /// 
        /// 
        public GithubLookupFacotry(
            IEnumerable providers,
            IOptionsMonitor options,
            ILogger logger)
        {
            this.providers = providers.OrderBy(item => item.Order);
            this.options = options;
            this.logger = logger;
        }
        /// 
        /// 查找域名与ip关系
        /// 
        /// 
        public async Task> LookupAsync(CancellationToken cancellationToken)
        {
            this.logger.LogInformation($"开始查找各域名的ip..");
            var hashSet = new HashSet();
            var domains = this.options.CurrentValue.Domains;
            foreach (var provider in this.providers)
            {
                var domainAddresses = await provider.LookupAsync(domains, cancellationToken);
                foreach (var item in domainAddresses)
                {
                    hashSet.Add(item);
                }
            }
            this.logger.LogInformation($"查找到{hashSet.Count}条域名ip记录");
            return hashSet;
        }
    }
}