package com.xypower.common;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URI;
import java.util.Enumeration;
import java.util.regex.Pattern;

public class NetworkUtils {
    // String regex = "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$";
    private static final Pattern IPV4_PATTERN = Pattern.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");

    private static final Pattern IPV6_STD_PATTERN = Pattern.compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");

    private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile("^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");

    public static boolean isIPv4Address(final String input) {
        if (TextUtils.isEmpty(input)) {
            return false;
        }
        return IPV4_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6StdAddress(final String input) {
        if (TextUtils.isEmpty(input)) {
            return false;
        }
        return IPV6_STD_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6HexCompressedAddress(final String input) {
        if (TextUtils.isEmpty(input)) {
            return false;
        }
        return IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches();
    }

    public static boolean isIPv6Address(final String input) {
        if (TextUtils.isEmpty(input)) {
            return false;
        }
        return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input);
    }

    public static String getMobileNetworkIp(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();

        if (networkInfos == null || networkInfos.length == 0) {
            return null;
        }

        for (NetworkInfo networkInfo : networkInfos) {
            if (networkInfo == null || networkInfo.getType() != ConnectivityManager.TYPE_MOBILE || !networkInfo.isConnected()) {
                continue;
            }

            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (inetAddress.isLoopbackAddress()) {
                            continue;
                        }
                        if (inetAddress instanceof Inet4Address) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return null;
    }


    public static int addAPN(Context context, String name, String desc, String numeric, String user, String pwd) {
        int id = -1;
        String NUMERIC = getSIMInfo(context);
        if (NUMERIC == null) {
            return -1;
        }
        Uri APN_URI = null;
        try {
            APN_URI = Uri.parse("content://telephony/carriers");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put("name", desc); //apn description
        values.put("apn", name);
        values.put("type", "default");   //apn Type
        values.put("numeric", numeric);
        values.put("mcc", numeric.substring(0, 3));
        values.put("mnc", numeric.substring(3, numeric.length()));
        values.put("proxy", "");
        values.put("port", "");
        values.put("mmsproxy", "");
        values.put("mmsport", "");
        values.put("user", user);
        values.put("server", "");                                       //服务器
        values.put("password", pwd);                                     //密码
        values.put("mmsc", "");                                          //MMSC
        Cursor c = null;
        Uri newRow = resolver.insert(APN_URI, values);
        if (newRow != null) {
            c = resolver.query(newRow, null, null, null, null);
            int idIndex = c.getColumnIndex("_id");
            c.moveToFirst();
            id = c.getShort(idIndex);
        }
        if (c != null)
            c.close();
        return id;
    }

    protected static String getSIMInfo(Context context) {
        TelephonyManager iPhoneManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return iPhoneManager.getSimOperator();
    }

    // 设置接入点
    public static void SetAPN(Context context, int id) {
        Uri CURRENT_APN_URI = null;
        try {
            CURRENT_APN_URI = Uri.parse("content://telephony/carriers");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put("apn_id", id);
        resolver.update(CURRENT_APN_URI, values, null, null);
    }

    /*
    public static void checkAPN(Context context) {
        // 检查当前连接的APN
        Cursor cr = context.getContentResolver().query(APN_URI, null, null, null, null);
        while (cr != null && cr.moveToNext()) {
            if(cr.getString(cr.getColumnIndex("apn")).equals("abc")){
                APN.hasAPN=true;
                break;
            }
        }
    }

     */

}
