package com.yidian.bcommon.utils

import android.content.Context
import android.net.ConnectivityManager
import android.telephony.TelephonyManager

class NetWorkUtils {
  companion object {
    private const val NET_TYPE_WIFI = "wifi"
    const val NET_TYPE_4G = "4g"
    const val NET_TYPE_5G = "5g"
    const val NET_TYPE_3G = "3g"
    const val NET_TYPE_2G = "2g"

    fun getNetWorkType(context: Context): String {
      var netType = "unknown"
      val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
      val networkInfo = manager.activeNetworkInfo ?: return netType
      val nType = networkInfo.type
      if (nType == ConnectivityManager.TYPE_WIFI) {
        netType = "wifi"
      } else if (nType == ConnectivityManager.TYPE_MOBILE) {
        val nSubType = networkInfo.subtype
        val telephonyManager: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        netType = if (nSubType == TelephonyManager.NETWORK_TYPE_NR) {
          "5g"
        } else if (nSubType == TelephonyManager.NETWORK_TYPE_LTE && !telephonyManager.isNetworkRoaming) {
          "4g"
        } else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA || (nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
            && !telephonyManager.isNetworkRoaming)
        ) {
          "3g"
        } else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS || nSubType == TelephonyManager.NETWORK_TYPE_EDGE || (nSubType == TelephonyManager.NETWORK_TYPE_CDMA
            && !telephonyManager.isNetworkRoaming)
        ) {
          "2g"
        } else {
          "unknown"
        }
      }
      return netType
    }

    fun isWifiConnected(context: Context): Boolean {
      return NET_TYPE_WIFI == getNetWorkType(context)
    }
  }
}
