package com.example.iot_controlhost.utils.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.global.HardwareSetting;
import com.example.iot_controlhost.utils.log.MyLog;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class NetState {
    /**
     * 信号质量(WIFI、4G)
     */
    public static int Semaphore = 0;

    /**
     * 判断网络连接方式
     *
     * @param context
     * @return 0:无网络 1:有线网络 2:WIFI 3:移动网络
     */
    public static int getNetworkType(Context context) {
        int result = 0;
        String lastIP = HardwareSetting.getIPAddress();
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                int networkType = info.getType();
                switch (networkType) {
                    case ConnectivityManager.TYPE_ETHERNET:
                        // 有线网络
                        String ethernetIpAddress = getEthernetIPAddress();
                        MMKVUtil.put(HardwareSetting.IP_ADDRESS, ethernetIpAddress);
                        result = 1;
                        break;
                    case ConnectivityManager.TYPE_WIFI:
                        // WIFI
                        String wifiIpAddress = getWifiIPAddress(context);
                        MMKVUtil.put(HardwareSetting.IP_ADDRESS, wifiIpAddress);
                        result = 2;
                        break;
                    case ConnectivityManager.TYPE_MOBILE:
                        // 移动网络
                        String mobileIpAddress = getMobileIPAddress();
                        MMKVUtil.put(HardwareSetting.IP_ADDRESS, mobileIpAddress);
                        result = 3;
                        break;
                }
            } else {
                MyLog.networkError("当前没有可用网络");
            }
        } else {
            MyLog.networkError("网络状态获取失败");
        }
        if (!lastIP.equals(HardwareSetting.getIPAddress())) {
            MyLog.test("IP地址发生变化：旧IP地址：" + lastIP + "，新IP地址：" + HardwareSetting.getIPAddress());
        }
        return result;
    }

    /**
     * 获取有线网络IPv4地址
      */
    private static String getEthernetIPAddress() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                if (iface.isUp() && !iface.isLoopback() && !iface.isVirtual()) {
                    Enumeration<InetAddress> addresses = iface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (!addr.isLoopbackAddress() && addr.getAddress().length == 4) {
                            return addr.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取WIFI网络IPv4地址
     */
    private static String getWifiIPAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            return intToIp(ipAddress);
        }
        return null;
    }

    /**
     * 获取移动网络IPv4地址
     * @return
     */
    private static String getMobileIPAddress() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                Enumeration<InetAddress> addresses = iface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (!addr.isLoopbackAddress() && addr.getAddress().length == 4) {
                        return addr.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将IP地址的整数形式转换成字符串形式
     */
    private static String intToIp(int ipAddress) {
        return (ipAddress & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                (ipAddress >> 24 & 0xFF);
    }
}
