using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using UnityEngine;

namespace Rokid.MRC
{
    //获取IP地址
    public class MRCUtility
    {
        public static List<string> interfaceList = new List<string>();

        /// <summary>
        /// 获取本机IP
        /// </summary>
        /// <param name="addType">要获取的IP类型</param>
        /// <returns></returns>
        public static List<string> GetLocalIP(AddressType addType)
        {
            interfaceList.Clear();

            if(addType == AddressType.IPv6 && !Socket.OSSupportsIPv6)
            {
                //如果想要IPv6，但是系统不支持
                return null;
            }

            string output = string.Empty;

            //遍历所有网卡NetworkInterface（真实和虚拟）
            foreach(NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                Debug.Log($"NetworkInterface Name : {networkInterface.Name}  Desc : {networkInterface.Description}");
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
                //无线网卡
                NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
                //以太网卡
                NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
                if((networkInterface.NetworkInterfaceType == _type1 || networkInterface.NetworkInterfaceType == _type2) && networkInterface.OperationalStatus == OperationalStatus.Up)
#endif
                {
                    //该网卡的所有IP地址
                    foreach(UnicastIPAddressInformation ip in networkInterface.GetIPProperties().UnicastAddresses)
                    {
                        if(addType == AddressType.IPv4)
                        {
                            //IPv4
                            if(ip.Address.AddressFamily == AddressFamily.InterNetwork)
                            {
                                interfaceList.Add($"Name : {networkInterface.Name}  IP : {ip.Address}");

                                Debug.Log($"Name : {networkInterface.Name}  IP : {ip.Address}");

                                output = ip.Address.ToString();
                            }
                        }
                        else if(addType == AddressType.IPv6)
                        {
                            //IPv6
                            if(ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
                            {
                                output = ip.Address.ToString();
                            }
                        }
                    }
                }
            }

            return interfaceList;
        }

        public static string GetWirelessIP(AddressType addType)
        {
            interfaceList.Clear();

            if(addType == AddressType.IPv6 && !Socket.OSSupportsIPv6)
            {
                //如果想要IPv6，但是系统不支持
                return null;
            }

            string output = string.Empty;

            //遍历所有网卡NetworkInterface（真实和虚拟）
            foreach(NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
                //无线网卡
                NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
                //以太网卡
                NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
                if((networkInterface.NetworkInterfaceType == _type1 || networkInterface.NetworkInterfaceType == _type2) && networkInterface.OperationalStatus == OperationalStatus.Up)
#endif
                {
                    //该网卡的所有IP地址
                    foreach(UnicastIPAddressInformation ip in networkInterface.GetIPProperties().UnicastAddresses)
                    {
                        if(addType == AddressType.IPv4)
                        {
                            //IPv4
                            if(ip.Address.AddressFamily == AddressFamily.InterNetwork && networkInterface.Name.Contains("wlan"))
                            {
                                interfaceList.Add($"Name : {networkInterface.Name}  IP : {ip.Address}");

                                Debug.Log($"Name : {networkInterface.Name}  IP : {ip.Address}");

                                output = ip.Address.ToString();

                                break;
                            }
                        }
                        else if(addType == AddressType.IPv6)
                        {
                            //IPv6
                            if(ip.Address.AddressFamily == AddressFamily.InterNetworkV6 && networkInterface.Name.Contains("wlan"))
                            {
                                output = ip.Address.ToString();
                                break;
                            }
                        }
                    }
                }
            }

            return output;
        }

        //本机的IP
        public static List<string> localAddresses = new List<string>();
        //本机所属的网段
        public static List<string> localSubAddresses = new List<string>();
        //获取本机的IP和网段
        public static void ScanLocalHost()
        {
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

            foreach(IPAddress ip in host.AddressList)
            {
                if(ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    //ipv4
                    string address = ip.ToString();
                    //局域网的网段
                    string subAddress = address.Remove(address.LastIndexOf('.'));

                    localAddresses.Add(address);

                    Debug.Log($"Addr : {address}  SubAddr : {subAddress}");

                    if(!localSubAddresses.Contains(subAddress))
                    {
                        localSubAddresses.Add(subAddress);
                    }
                }
            }
        }

        public static IPAddress[] GetLoacalIpv4()
        {
            IPAddress[] addresses = Dns.GetHostAddresses("localhost");
            return (from x in addresses where x.AddressFamily == AddressFamily.InterNetwork select x).ToArray();
        }

        public static IPAddress[] GetLoacalIpv6()
        {
            IPAddress[] addresses = Dns.GetHostAddresses("localhost");
            return (from x in addresses where x.AddressFamily == AddressFamily.InterNetworkV6 select x).ToArray();
        }

        //通过请求外网IP
        public static string GetOutSideIP()
        {
            using(WebClient wc = new WebClient())
            {
                return wc.DownloadString(@"http://icanhazip.com/").Replace("\n", "");
            }
        }
    }

    public enum AddressType
    {
        IPv4, IPv6
    }
}