package com.ycgis.macall.personalcenter.util;

import android.os.Build;
import android.util.Log;

import com.rs.macall.androidx.basemodel.utils.LogUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

/**
 * created by:   Macall
 * create time:  2024/1/17 16:55
 * copyright:    @ruansee.com
 * Describe:
 */
public class IPAddressUtils {
    private static final String IPV4_BASIC_PATTERN_STRING = "(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){1}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])";
    private static final Pattern IPV4_PATTERN = Pattern.compile("^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){1}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
    private static final Pattern IPV4_MAPPED_IPV6_PATTERN = Pattern.compile("^::[fF]{4}:(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){1}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
    private static final Pattern IPV6_STD_PATTERN = Pattern.compile("^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$");
    private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile("^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)::(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$");
    private static final char COLON_CHAR = ':';
    private static final int MAX_COLON_COUNT = 7;

    private IPAddressUtils() {

    }

    public static boolean isIPv4Address(String input) {
        return IPV4_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv4MappedIPv64Address(String input) {
        return IPV4_MAPPED_IPV6_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6StdAddress(String input) {
        return IPV6_STD_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6HexCompressedAddress(String input) {
        int colonCount = 0;

        for(int i = 0; i < input.length(); ++i) {
            if (input.charAt(i) == ':') {
                ++colonCount;
            }
        }

        return colonCount <= 7 && IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6Address(String input) {
        return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input);
    }

    public static String getLocalIpAddress() {
        List<String> list = new ArrayList<>();
        try {
            String ipv4;
            ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ni : nilist) {
                ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                for (InetAddress address : ialist) {
                    if (!address.isLoopbackAddress()) {
                        ipv4 = address.getHostAddress();
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                            if (isIPv4Address(ipv4)) {
                                list.add(ipv4);
//                                return ipv4;
                            }
                        } else {
                            if (address instanceof Inet4Address) {
                                list.add(ipv4);
//                                return ipv4;
                            }
                        }
                    }
                }
            }
            if (!list.isEmpty()){
                if (list.size() ==1)
                    return list.get(0);
                for (String ip :list) {
                    if (ip.startsWith("127.0."))continue;
                    if (ip.startsWith("192.168."))continue;
                    return ip;
                }
            }
            return ipAddress();
        } catch (SocketException ex) {
            Log.e("localip", ex.toString());
            return ipAddress();
        }
    }

    public static String ipAddress() {
        try {
            for (final Enumeration<NetworkInterface> enumerationNetworkInterface = NetworkInterface.getNetworkInterfaces(); enumerationNetworkInterface.hasMoreElements(); ) {
                final NetworkInterface networkInterface = enumerationNetworkInterface.nextElement();
                for (Enumeration<InetAddress> enumerationInetAddress = networkInterface.getInetAddresses(); enumerationInetAddress.hasMoreElements(); ) {
                    final InetAddress inetAddress = enumerationInetAddress.nextElement();
                    final String ipAddress = inetAddress.getHostAddress();
                    if (!inetAddress.isLoopbackAddress()){
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                            if (isIPv4Address(ipAddress)) {
                                return ipAddress;
                            }
                        } else {
                            if (inetAddress instanceof Inet4Address) {
                                return ipAddress;
                            }
                        }
                    }
                }
            }
            return "127.0.0.1";
        } catch (final Exception e) {
            LogUtils.e("获取Ip失败：" + e.getMessage());
            return "127.0.0.1";
        }
    }
}
