using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DotRas;

namespace StartServerWPF.Modules.Main
{
    public class VPNHelper
    {
        public RasDialer dialer;
        public RasHandle handle;
        public RasConnection connect;
        //public RasPhoneBook allUsersPhoneBook;
        // VPN地址
        public string IPToPing { get; set; }

        // VPN名称
        public string VPNName { get; set; }

        // VPN用户名
        public string UserName { get; set; }

        // VPN密码
        public string PassWord { get; set; }

        public VPNHelper(string vpnName, string vpnIP, string userName, string passWord)
        {
            VPNName = vpnName;
            IPToPing = vpnIP;
            UserName = userName;
            PassWord = passWord;
            dialer = new RasDialer();
            dialer.EntryName = vpnName;
            dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

        }
        public VPNHelper()
        {

        }

        /// <summary>
        /// 尝试连接VPN
        /// </summary>
        /// <returns></returns>
        public string ConnectVPN(string vpnName, string userName, string passWord)
        {
            try
            {
                dialer.EntryName = vpnName;
                // Set the credentials the dialer should use.
                dialer.Credentials = new NetworkCredential(userName, passWord);

                // NOTE: The entry MUST be in the phone book before the connection can be dialed.
                // Begin dialing the connection; this will raise events from the dialer instance.
                handle = dialer.DialAsync();
                return "VPN连接成功！";
                // Enable the disconnect button for use later.
                //this.DisconnectButton.Enabled = true;
            }
            catch (Exception ex)
            {
                return ex.ToString();
                //this.StatusTextBox.AppendText(ex.ToString());
            }
        }


        /// <summary>
        /// 尝试断开连接(默认VPN)
        /// </summary>
        /// <returns></returns>
        [Obsolete]
        public void DisConnectVPN(string vpnName)
        {
            if (dialer.IsBusy)
            {
                // The connection attempt has not been completed, cancel the attempt.
                dialer.DialAsyncCancel();
            }
            else
            {
                // The connection attempt has completed, attempt to find the connection in the active connections.
                RasConnection connection = RasConnection.GetActiveConnectionByName(vpnName, dialer.PhoneBookPath);
                if (connection != null)
                {
                    // The connection has been found, disconnect it.
                    connection.HangUp();

                }
            }
        }

        /// <summary>
        /// 创建或更新一个VPN连接(指定VPN名称，及IP)
        /// </summary>
        [Obsolete]
        public void CreateOrUpdateVPN(string updateVPNname, string updateVPNip)
        {
            RasDialer dialer = new RasDialer();
            RasPhoneBook allUsersPhoneBook = new RasPhoneBook();

            allUsersPhoneBook.Open();

            // 如果已经该名称的VPN已经存在，则更新这个VPN服务器地址
            if (allUsersPhoneBook.Entries.Contains(updateVPNname))
            {
                allUsersPhoneBook.Entries[updateVPNname].PhoneNumber = updateVPNip;
                // 不管当前VPN是否连接，服务器地址的更新总能成功，如果正在连接，则需要VPN重启后才能起作用
                allUsersPhoneBook.Entries[updateVPNname].Update();
            }
            // 创建一个新VPN
            else
            {
                RasEntry entry = RasEntry.CreateVpnEntry(updateVPNname,
                    updateVPNip, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
                allUsersPhoneBook.Entries.Add(entry);
                dialer.EntryName = updateVPNname;
                dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
            }
        }

        [Obsolete]
        public bool CheckVpnStatus(string vpnName)
        {
            var host =Dns.GetHostEntry(Dns.GetHostName());
           var ip= host.AddressList.Where(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
            && i.ToString().Contains("172.16.30")).FirstOrDefault();
                     
            return ip != null ? true : false;
            //  RasConnection connection = RasConnection.GetActiveConnectionByName(vpnName, dialer.PhoneBookPath);

            // return connection != null ? true : false;
        }
        /// <summary>
        /// 删除指定名称的VPN
        /// 如果VPN正在运行，一样会在电话本里删除，但是不会断开连接，所以，最好是先断开连接，再进行删除操作
        /// </summary>
        /// <param name="delVpnName"></param>
        [Obsolete]
        public void TryDeleteVPN(string delVpnName)
        {
            RasDialer dialer = new RasDialer();
            RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
            allUsersPhoneBook.Open();
            if (allUsersPhoneBook.Entries.Contains(delVpnName))
            {
                allUsersPhoneBook.Entries.Remove(delVpnName);
            }
        }
        /// <summary>
        /// 获取VPN IP,如果无172地址，则未连接VPN
        /// </summary>
        public string GetLocalIp()
        {
            // 获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                    if (AddressIP.Contains("172.16"))
                    {
                        return AddressIP;
                    }
                }
            }
            return AddressIP;
        }

    }
}
