package com.casic.common.detector.gd.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationListener
import android.location.LocationManager
import android.os.Handler
import android.os.Looper
import androidx.core.app.ActivityCompat
import androidx.core.location.GnssStatusCompat
import androidx.core.location.LocationManagerCompat
import com.pengxh.kt.lite.extensions.getSystemService
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.SaveKeyValues

object RtkLocationTool {
    fun getCurrentLocation(context: Context, rtkLocationListener: LocationListener) {
        if (ActivityCompat.checkSelfPermission(
                context, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS
            ) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(
                context, Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(
                context, Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            "缺少定位权限".show(context)
            return
        }
        val locationManager = context.getSystemService<LocationManager>() ?: return
        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 0, 0f
        ) {
            rtkLocationListener.onLocationChanged(it)
        }

        LocationManagerCompat.registerGnssStatusCallback(
            locationManager, object : GnssStatusCompat.Callback() {
                override fun onSatelliteStatusChanged(status: GnssStatusCompat) {
                    super.onSatelliteStatusChanged(status)
                    // 可以搜索到的卫星总数
                    val satelliteCount = status.satelliteCount
                    var effectiveCount = 0
                    for (index in 0 until satelliteCount) {
                        /**
                         * 每个卫星的载波噪声密度，噪声密度越大，信号越强。
                         * <br>
                         * 参考：https://juejin.cn/post/7144313606329335815
                         * */
                        val cn0DbHz = status.getCn0DbHz(index)
                        if (cn0DbHz > 20) {
                            effectiveCount++
                        }
                    }
                    SaveKeyValues.putValue(LocaleConstant.SATELLITE_EFFECTIVE_COUNT, effectiveCount)
                }
            }, Handler(Looper.getMainLooper())
        )
    }
}