package com.ytpm.hydtw.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.wifi.WifiManager
import android.os.Build
import android.text.format.Formatter
import java.net.Inet4Address
import java.net.NetworkInterface
import java.util.*

class GameNetworkUtils(private val context: Context) {

    /**
     * 获取当前连接的网络类型
     */
    fun getConnectionType(): String {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork ?: return "无连接"
            val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return "无连接"

            when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "Wi-Fi"
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "移动数据"
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "以太网"
                else -> "其他网络"
            }
        } else {
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo
            networkInfo?.typeName ?: "无连接"
        }
    }

    /**
     * 获取 Wi-Fi 连接的 IP 地址
     */
    fun getWifiIpAddress(): String? {
        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        if (!wifiManager.isWifiEnabled) {
            return null
        }

        val ipAddress = wifiManager.connectionInfo.ipAddress

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            Formatter.formatIpAddress(ipAddress)
        } else {
            String.format(
                "%d.%d.%d.%d",
                (ipAddress and 0xff),
                (ipAddress shr 8 and 0xff),
                (ipAddress shr 16 and 0xff),
                (ipAddress shr 24 and 0xff)
            )
        }
    }

    /**
     * 获取移动数据连接的 IP 地址
     */
    fun getMobileIpAddress(): String? {
        return try {
            val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
            for (intf in interfaces) {
                // 查找移动数据接口（通常以 rmnet 或 ppp 开头）
                if (intf.name.startsWith("rmnet") || intf.name.startsWith("ppp")) {
                    val addrs = Collections.list(intf.inetAddresses)
                    for (addr in addrs) {
                        if (!addr.isLoopbackAddress && addr is Inet4Address) {
                            return addr.hostAddress
                        }
                    }
                }
            }
            null
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 获取当前连接的 IP 地址（自动判断网络类型）
     */
    fun getCurrentIpAddress(): String? {
        return when (getConnectionType()) {
            "Wi-Fi" -> getWifiIpAddress()
            "移动数据" -> getMobileIpAddress()
            else -> null
        }
    }

    /**
     * 获取所有网络接口的 IP 地址
     */
    fun getAllIpAddresses(): List<String> {
        val ipAddresses = mutableListOf<String>()

        try {
            val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
            for (intf in interfaces) {
                val addrs = Collections.list(intf.inetAddresses)
                for (addr in addrs) {
                    if (!addr.isLoopbackAddress) {
                        val sAddr = addr.hostAddress
                        ipAddresses.add(sAddr)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return ipAddresses
    }
}