using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
namespace FastGithub.Configuration
{
    /// 
    /// 反向代理端口
    /// 
    public static class ReverseProxyPort
    {
        /// 
        /// ssh端口
        /// 
        public static int Ssh { get; }
        /// 
        /// http端口
        /// 
        public static int Http { get; }
        /// 
        /// https端口
        /// 
        public static int Https { get; }
        /// 
        /// 反向代理端口
        /// 
        static ReverseProxyPort()
        {
            var ports = new TcpListenerPortCollection();
            Ssh = OperatingSystem.IsWindows() ? ports.GetAvailablePort(22) : ports.GetAvailablePort(3822);
            Http = OperatingSystem.IsWindows() ? ports.GetAvailablePort(80) : ports.GetAvailablePort(3880);
            Https = OperatingSystem.IsWindows() ? ports.GetAvailablePort(443) : ports.GetAvailablePort(38443);
        }
        /// 
        /// 已监听的tcp端口集合
        /// 
        private class TcpListenerPortCollection
        {
            private readonly HashSet tcpPorts = new();
            /// 
            /// 已监听的tcp端口集合
            /// 
            public TcpListenerPortCollection()
            {
                var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
                foreach (var endpoint in tcpListeners)
                {
                    this.tcpPorts.Add(endpoint.Port);
                }
            }
            /// 
            /// 获取可用的随机Tcp端口
            /// 
            ///  
            /// 
            public int GetAvailablePort(int minValue)
            {
                for (var port = minValue; port < IPEndPoint.MaxPort; port++)
                {
                    if (this.tcpPorts.Contains(port) == false)
                    {
                        return port;
                    }
                }
                throw new FastGithubException("当前无可用的端口");
            }
        }
    }
}