package com.zxhy.solarmasterace.permission

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import com.zxhy.solarmasterace.quicktools.ActivityLauncher
import com.zxhy.solarmasterace.quicktools.settingManageExternalStorage

//Android 13以后,读写权限无法弹出系统弹窗,分化为Manifest.permission.READ_MEDIA_*权限
//Android 11以后,Manifest.permission.READ_EXTERNAL_STORAGE 授予后还需授予 额外储存管理权限 ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
//Android 11以下使用Manifest.permission.READ_EXTERNAL_STORAGE
@SuppressLint("LocalSuppress")
fun Context.requestStoreFollow(
    activityLauncher: ActivityLauncher,
    disAgreeAction: (() -> Unit)? = null,
    agreeAction: (() -> Unit)? = null,
) {

    //请求读写管理权限
    @SuppressLint("NewApi")
    val requestExternalStorageManager: () -> Unit = {
        if (!Environment.isExternalStorageManager()) {
            val uri = Uri.parse("package:$packageName")
            val intent = settingManageExternalStorage(uri)
            activityLauncher.launch(intent) {
                val flag = Environment.isExternalStorageManager()
                if (flag) agreeAction?.invoke() else disAgreeAction?.invoke()
            }
        } else {
            agreeAction?.invoke()
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {//Android 13以后
        requestExternalStorageManager()
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {//Android 11以后
        requestPermission(
            this, activityLauncher,
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), "Set permission to access external storage",
            agreeAction = { //读写权限通过,设置储存管理权限
                requestExternalStorageManager()
            },
            disAgreeAction = { disAgreeAction?.invoke() }
        )
    } else { //Android 11以下,Android 6以上
        requestPermission(
            this, activityLauncher,
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), "Set permission to access external storage",
            agreeAction = {
                //读写权限通过
                agreeAction?.invoke()
            }, disAgreeAction = { disAgreeAction?.invoke() }
        )
    }
}
