using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace FastGithub
{
    /// 
    /// FastGithub的配置
    /// 
    public class FastGithubOptions
    {
        /// 
        /// 域名
        /// 
        private DomainMatch[]? domainMatches;
        /// 
        /// 受信任的dns服务
        /// 
        public DnsIPEndPoint TrustedDns { get; set; } = new DnsIPEndPoint { IPAddress = "127.0.0.1", Port = 5533 };
        /// 
        /// 不受信任的dns服务
        /// 
        public DnsIPEndPoint UntrustedDns { get; set; } = new DnsIPEndPoint { IPAddress = "114.114.114.114", Port = 53 };
        /// 
        /// 代理的域名匹配
        /// 
        public HashSet DomainMatches { get; set; } = new();
        /// 
        /// 是否匹配指定的域名
        /// 
        /// 
        /// 
        public bool IsMatch(string domain)
        {
            if (this.domainMatches == null)
            {
                this.domainMatches = this.DomainMatches.Select(item => new DomainMatch(item)).ToArray();
            }
            return this.domainMatches.Any(item => item.IsMatch(domain));
        }
        /// 
        /// 域名匹配
        /// 
        private class DomainMatch
        {
            private readonly Regex regex;
            private readonly string pattern;
            /// 
            /// 域名匹配
            /// 
            /// 域名表达式
            public DomainMatch(string pattern)
            {
                this.pattern = pattern;
                var regexPattern = Regex.Escape(pattern).Replace(@"\*", ".*");
                this.regex = new Regex($"^{regexPattern}$", RegexOptions.IgnoreCase);
            }
            /// 
            /// 是否与指定域名匹配
            /// 
            /// 
            /// 
            public bool IsMatch(string domain)
            {
                return this.regex.IsMatch(domain);
            }
            /// 
            /// 转换为文本
            /// 
            /// 
            public override string ToString()
            {
                return this.pattern;
            }
        }
    }
}