package com.ama.core.architecture.util

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.wifi.WifiManager
import com.ama.core.architecture.BaseApp
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface

@SuppressLint("StaticFieldLeak")
object NetUtil {
    val context = BaseApp.appContext()
    /**
     * 获取本机IPv4地址
     * @param context 上下文对象
     * @return IPv4地址字符串，无网络连接时返回null
     */
    fun getLocalIpAddress(): String? {
        return when (getNetworkType()) {
            NetworkType.WIFI -> getWifiIpAddress()
            NetworkType.MOBILE -> getMobileIpAddress()
            NetworkType.NONE -> null // 无网络连接
        }
    }

    /**
     * 获取当前网络类型
     */
    private fun getNetworkType(): NetworkType {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val network = connectivityManager.activeNetwork ?: return NetworkType.NONE
        val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return NetworkType.NONE

        return when {
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> NetworkType.WIFI
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> NetworkType.MOBILE
            else -> NetworkType.NONE
        }
    }

    /**
     * 获取Wi-Fi网络下的IP地址
     */
    private fun getWifiIpAddress(): String? {
        return try {
            val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
            val wifiInfo = wifiManager.connectionInfo
            val ipAddress = wifiInfo.ipAddress
            intToIp(ipAddress)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 获取移动数据网络下的IP地址
     */
    private fun getMobileIpAddress(): String? {
        return try {
            val interfaces: java.util.Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val networkInterface = interfaces.nextElement()
                val addresses: java.util.Enumeration<InetAddress> = networkInterface.inetAddresses
                while (addresses.hasMoreElements()) {
                    val address = addresses.nextElement()
                    // 过滤回环地址、链路本地地址，且只返回IPv4地址[2,3](@ref)
                    if (!address.isLoopbackAddress && !address.isLinkLocalAddress && address is Inet4Address) {
                        return address.hostAddress
                    }
                }
            }
            null
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 将整数形式的IP地址转换为字符串[1,2,4](@ref)
     */
    private fun intToIp(ipAddress: Int): String {
        return "${(ipAddress and 0xFF)}.${(ipAddress shr 8 and 0xFF)}.${(ipAddress shr 16 and 0xFF)}.${(ipAddress shr 24 and 0xFF)}"
    }

    private enum class NetworkType {
        WIFI, MOBILE, NONE
    }
}