package com.lovense.sdkdemo

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity.LOCATION_SERVICE
import androidx.core.app.ActivityCompat
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions

/**
 * Date: 2025/03/10
 * Desc: Permission
 */
object RequestPermission {

    @JvmStatic
    fun bluetooth(): Array<String> {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.BLUETOOTH_ADVERTISE,
            )
        } else {
            arrayOf(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
            )
        }
    }


    /**
     * Check And Granted Bluetooth Permission
     */
    fun checkAndGrantedBluetoothPermission(activity: Activity, nextDo: () -> Unit) {
        val permission = checkBluetoothPermissionsEnable(activity)
//        LogUtils.i("checkBluetoothPermission___permission: $permission")
        if (!permission) {
            XXPermissions.with(activity).permission(RequestPermission.bluetooth())
                .request(object : OnPermissionCallback {

                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
//                        LogUtils.i("checkBluetoothPermission - onGranted - allGranted: $allGranted")
                        if (allGranted) {
                            permissionDone(activity, nextDo)
                        } else {
                            permissionDenied()
                        }
                    }

                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
//                        LogUtils.i("checkBluetoothPermission - onDenied - doNotAskAgain: $doNotAskAgain")
                        permissionDenied()
                    }

                    private fun permissionDenied() {
                        permissionDone(activity, nextDo)
                    }

                })
        } else {
//            LogUtils.i("checkBluetoothPermission - has")
            permissionDone(activity, nextDo)
        }
    }

    private fun permissionDone(activity: Activity, nextDo: () -> Unit) {
        // check - bluetooth permissions enable
        if (!checkBluetoothPermissionsEnable(activity)){
            Toast.makeText(activity, "Bluetooth permission denied", Toast.LENGTH_SHORT).show()
            return
        }
        // check - bluetooth enable
        if (!checkBluetoothEnable(activity) ) {
            Toast.makeText(activity, "Bluetooth is not enabled", Toast.LENGTH_SHORT).show()
            return
        }
        // check - gps enable
        if (!isOPenGps(activity)) {
            Toast.makeText(activity, "Please open the gps.", Toast.LENGTH_SHORT).show()
            return
        }

        // next to do
        nextDo()
    }

    /**
     * Check - Bluetooth Permissions
     */
    fun checkBluetoothPermissionsEnable(activity: Activity): Boolean = XXPermissions.isGranted(activity, bluetooth())

    /**
     * Check - Bluetooth Enable
     */
    fun checkBluetoothEnable(activity: Activity): Boolean = checkBTEnable(activity.application, true)

    /**
     * isEnable Bluetooth
     */
    fun checkBTEnable(context: Context, promptEnable: Boolean): Boolean {
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null) {
            Log.d("RequestPermission", "not support bluetooth")
            return false
        }
        if (bluetoothAdapter.isEnabled) {
            return true
        }
        if (promptEnable && ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
            val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            enableIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(enableIntent)
        }
        return false
    }


    /**
     * isStarted GPS or AGPS
     *
     * @param context
     * @return true isStarted
     */
    private fun isOPenGps(context: Context): Boolean {
        if (Build.VERSION.SDK_INT in Build.VERSION_CODES.M..Build.VERSION_CODES.R ) {
            val locationManager = context.getSystemService(LOCATION_SERVICE) as LocationManager
            val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            val network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            return (gps || network)
        } else {
            return true
        }
    }

}
