package com.mogo.v2x.utils

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.telephony.CellLocation
import android.telephony.TelephonyManager
import android.telephony.cdma.CdmaCellLocation
import android.telephony.gsm.GsmCellLocation
import java.lang.Exception

internal class DeviceUtils {

    companion object {

        @SuppressLint("MissingPermission")
        @JvmStatic
        fun getCellId(context: Context): String? {
            val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            val pm = context.packageManager
            val accessCoarseLocationPermission = PackageManager.PERMISSION_GRANTED ==
                    pm.checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION, context.packageName)
            val accessFineLocationPermission = PackageManager.PERMISSION_GRANTED ==
                    pm.checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, context.packageName)
            if (!accessCoarseLocationPermission || !accessFineLocationPermission) return "noPermission"
            var location: CellLocation? = null
            try {
                location = tm.cellLocation
            } catch (e: Exception) {
                e.printStackTrace()
            }
            if (location != null) {
                // Gsm网络 , 联通移动的网络属于这一套
                if (location is GsmCellLocation) {
                    val cellid = location.cid
                    return cellid.toString()
                    // Cdma网络 , 电信网络属于这一种
                } else if (location is CdmaCellLocation) {
                    return location.baseStationId.toString()
                }
            }
            return null
        }
    }
}