package com.base.locationsharewhite.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.core.app.ActivityCompat
import com.base.locationsharewhite.utils.IntentUtils.intentAppDetailsSettings

object PermissionUtils {

    fun Context.checkStorePermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            val readPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            val writePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;
        }
    }

    fun Context.checkNotificationPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
        } else {
            return true
        }
    }

    fun Context.checkLocationPermission(): Boolean {

        val fineLocationPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val accessCoarsePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)

        return fineLocationPermission == PackageManager.PERMISSION_GRANTED && accessCoarsePermission == PackageManager.PERMISSION_GRANTED;
    }


    fun Activity.checkLocationPermissionDeniedByUser(): Boolean {

        val deniedByUser1 =
            !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val deniedByUser2 =
            !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)

        LogEx.logDebug("checkLocationPermissionDeniedByUser", "accessCoarsePermission=$deniedByUser1")
        LogEx.logDebug("checkLocationPermissionDeniedByUser", "fineLocationPermission=$deniedByUser2")

        return deniedByUser1 && deniedByUser2
    }


    fun Context.checkBackgroundLocationPermission(): Boolean {
        return ActivityCompat.checkSelfPermission(
            this, Manifest.permission.ACCESS_BACKGROUND_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    }

    fun Activity.checkBackgroundLocationPermissionDeniedByUser(): Boolean {
        val deniedByUser1 =
            !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
        return deniedByUser1
    }

    fun Context.requestStoragePermission(
        launcher: ActivityLauncher,
        jumpAction: (() -> Unit)? = null,
        result: (flag: Boolean) -> Unit
    ) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val intent =
                Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
            intent.addCategory("android.intent.category.DEFAULT")
            intent.data = Uri.parse("package:${packageName}")
            jumpAction?.invoke()
            launcher.launch(intent) {
                result.invoke(checkStorePermission())
            }
        } else {
            launcher.launch(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { map ->
                result(map.values.all { it })
            }
        }

    }


    fun Activity.requestLocationAllowAllTime(
        launcher: ActivityLauncher,
        jumpOutAction: (() -> Unit)? = null,//跳转到设置
        permissionAllowAction: (() -> Unit)? = null//权限同意
    ) {

        val TAG = "requestLocationAllowAllTime"

        launcher.launch(
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
            )
        ) { map ->
            val result = map.values.all { it }
            LogEx.logDebug(TAG, "定位权限回调 result=$result")
            if (result) {
                //跳转到后台位置设置
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    launcher.launch(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) { map ->
                        val backLocationResult = map.values.all { it }
                        LogEx.logDebug(TAG, "后台位置权限回调 backLocationResult=$backLocationResult")
                        if (backLocationResult) {
//                            toast("权限请求完毕")
                            permissionAllowAction?.invoke()
                        } else {
                            val userBackLocationDeny = this.checkBackgroundLocationPermissionDeniedByUser()
                            LogEx.logDebug(TAG, "userBackLocationDeny userBackLocationDeny=$userBackLocationDeny 跳转设置")
                            if (userBackLocationDeny) {
                                jumpOutAction?.invoke()
                                launcher.launch(intentAppDetailsSettings(this))
                            }
                        }
                    }
                } else {
                    permissionAllowAction?.invoke()
//                    toast("权限请求完毕")
                }
            } else {
                val userDeny = checkLocationPermissionDeniedByUser()
                LogEx.logDebug(TAG, "userDeny userDeny=$userDeny 跳转设置")
                if (userDeny) {
                    jumpOutAction?.invoke()
                    launcher.launch(intentAppDetailsSettings(this))
                }
            }
        }
    }
}