using Microsoft.Extensions.Hosting;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
namespace FastGithub.Dns
{
    /// 
    /// dns拦截后台服务
    /// 
    [SupportedOSPlatform("windows")]
    sealed class DnsInterceptHostedService : BackgroundService
    {
        private readonly DnsInterceptor dnsInterceptor;
        private readonly IEnumerable conflictSolvers;
        /// 
        /// dns拦截后台服务
        ///  
        /// 
        /// 
        public DnsInterceptHostedService(
            DnsInterceptor dnsInterceptor,
            IEnumerable conflictSolvers)
        {
            this.dnsInterceptor = dnsInterceptor;
            this.conflictSolvers = conflictSolvers;
        }
        /// 
        /// 启动时处理冲突
        /// 
        /// 
        /// 
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            foreach (var solver in this.conflictSolvers)
            {
                await solver.SolveAsync(cancellationToken);
            }
            await base.StartAsync(cancellationToken);
        }
        /// 
        /// 停止时恢复冲突
        /// 
        /// 
        /// 
        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            foreach (var solver in this.conflictSolvers)
            {
                await solver.RestoreAsync(cancellationToken);
            }
            await base.StopAsync(cancellationToken);
        }
        /// 
        /// dns后台
        /// 
        /// 
        /// 
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Yield();
            this.dnsInterceptor.Intercept(stoppingToken);
        }
    }
}