package com.xty.common.bracelet

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import androidx.core.content.ContextCompat
import com.mylhyl.acp.Acp
import com.mylhyl.acp.AcpListener
import com.mylhyl.acp.AcpOptions
import com.xty.common.LogUtils


/**
 * 蓝牙权限
 */
var bluePermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    arrayOf(
        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.BLUETOOTH_ADVERTISE,
        Manifest.permission.BLUETOOTH_SCAN,
        Manifest.permission.BLUETOOTH_ADMIN,
        Manifest.permission.BLUETOOTH_CONNECT,
        Manifest.permission.BLUETOOTH
    )
} else {
    arrayOf(
        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION,
    )
}

/**
 * 获取蓝牙权限
 */
fun getBluePermission(context: Context, result: (granted: Boolean) -> Unit){
    Acp.getInstance(context).request(
        AcpOptions.Builder()
            .setPermissions(
                *bluePermissions
            ).build(),
        object : AcpListener {
            override fun onGranted() {
               result.invoke(true)
            }

            override fun onDenied(permissions: List<String>) {
                result.invoke(false)
            }
        })
}



/**
 * 检查蓝牙权限
 */
fun checkBlueConnectPermission(context: Context): Boolean{
    return checkPermissionAllGranted(context, bluePermissions)
}

/**
 * GPS开关是否打开
 */
fun isGpsOpen(context: Context): Boolean {
    val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
    val gps: Boolean = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
    // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
    val network: Boolean = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    return gps || network
}

/**
 * 检查是否获取所有权限
 */
fun checkPermissionAllGranted(context: Context, permissions: Array<String>): Boolean {
    for (str in permissions) {
        LogUtils.d("test-----:buildVersion:${Build.VERSION.SDK_INT};;;permission:$str")
        // 只要有一个权限没有被授予, 则直接返回 false
        if (  ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
            LogUtils.d("test-----:notPermission:$str")
            return false
        }
    }
    return true
}