package com.framework.app.tools

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.net.wifi.WifiManager
import android.os.Build
import android.text.TextUtils
import androidx.core.content.ContextCompat
import com.framework.app.tools.MacUtil
import java.lang.StringBuilder
import java.net.NetworkInterface
import java.net.SocketException

/**
 * Created by weimo on 2020/7/13.
 */
object MacUtil {
    @SuppressLint("HardwareIds")
    fun getMacAddress(context: Context): String? {
        if (Build.VERSION.SDK_INT >= 23) {
            val str = getMacMoreThanM(context)
            if (!TextUtils.isEmpty(str)) {
                return str
            }
        } else {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_WIFI_STATE)
                == PackageManager.PERMISSION_GRANTED
            ) {
                val wifiManager = context.applicationContext
                    .getSystemService(Context.WIFI_SERVICE) as WifiManager
                if (null != wifiManager) {
                    return wifiManager.connectionInfo.macAddress
                }
            }
        }
        return null
    }

    /**
     * android 6.0+获取wifi的mac地址
     * @param paramContext
     * @return
     */
    private fun getMacMoreThanM(paramContext: Context): String? {
        try {
            //获取本机器所有的网络接口
            val enumeration = NetworkInterface.getNetworkInterfaces()
            while (enumeration.hasMoreElements()) {
                val networkInterface = enumeration.nextElement()
                //获取硬件地址，一般是MAC
                val arrayOfByte = networkInterface.hardwareAddress
                if (arrayOfByte == null || arrayOfByte.size == 0) {
                    continue
                }
                val stringBuilder = StringBuilder()
                for (b in arrayOfByte) {
                    //格式化为：两位十六进制加冒号的格式，若是不足两位，补0
                    stringBuilder.append(
                        String.format(
                            "%02X:",
                            *arrayOf<Any>(java.lang.Byte.valueOf(b))
                        )
                    )
                }
                if (stringBuilder.length > 0) {
                    //删除后面多余的冒号
                    stringBuilder.deleteCharAt(stringBuilder.length - 1)
                }
                val str = stringBuilder.toString()
                // wlan0:无线网卡 eth0：以太网卡
                if (networkInterface.name == "wlan0") {
                    return str
                }
            }
        } catch (socketException: SocketException) {
            return null
        }
        return null
    }
}