package com.test.basd.fastcleanerjunk.helps

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils

object PermissionHelp {
    fun checkStorePermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            PermissionUtils.isGranted(PermissionConstants.STORAGE)
        }
    }

    fun Context.requestStorePermission(
        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 {
            PermissionUtils.permissionGroup(PermissionConstants.STORAGE).callback { isAllGranted, _, _, _ ->
                result.invoke(isAllGranted)
            }
        }

    }
}