using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace FastGithub.DomainResolve
{
    /// 
    /// DnscryptProxy服务
    /// 
    sealed class DnscryptProxy
    {
        private const string name = "dnscrypt-proxy";
        /// 
        /// 相关进程
        /// 
        private Process? process;
        /// 
        /// 获取监听的节点
        /// 
        public IPEndPoint EndPoint { get; }
        /// 
        /// DnscryptProxy服务
        /// 
        /// 监听的节点
        public DnscryptProxy(IPEndPoint endPoint)
        {
            this.EndPoint = endPoint;
        }
        /// 
        /// 启动dnscrypt-proxy
        /// 
        /// 
        /// 
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var tomlPath = $"{name}.toml";
            await TomlUtil.SetListensAsync(tomlPath, this.EndPoint, cancellationToken);
            await TomlUtil.SetEdnsClientSubnetAsync(tomlPath, cancellationToken);
            foreach (var process in Process.GetProcessesByName(name))
            {
                process.Kill();
                process.WaitForExit();
            }
            if (OperatingSystem.IsWindows())
            {
                StartDnscryptProxy("-service uninstall")?.WaitForExit();
                StartDnscryptProxy("-service install")?.WaitForExit();
                StartDnscryptProxy("-service start")?.WaitForExit();
                this.process = Process.GetProcessesByName(name).FirstOrDefault(item => item.SessionId == 0);
            }
            else
            {
                this.process = StartDnscryptProxy(string.Empty);
            }
        }
        /// 
        /// 停止dnscrypt-proxy
        /// 
        public void Stop()
        {
            if (OperatingSystem.IsWindows())
            {
                StartDnscryptProxy("-service stop")?.WaitForExit();
                StartDnscryptProxy("-service uninstall")?.WaitForExit();
            }
            if (this.process != null && this.process.HasExited == false)
            {
                this.process.Kill();
            }
        }
        /// 
        /// 启动DnscryptProxy进程
        /// 
        ///  
        private static Process? StartDnscryptProxy(string arguments)
        {
            return Process.Start(new ProcessStartInfo
            {
                FileName = OperatingSystem.IsWindows() ? $"{name}.exe" : name,
                Arguments = arguments,
                UseShellExecute = true,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden
            });
        }
        /// 
        /// 转换为字符串
        /// 
        /// 
        public override string ToString()
        {
            return name;
        }
    }
}