package com.zxhy.hfilemanagermaster.permission

import android.Manifest
import android.annotation.SuppressLint
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.annotation.RequiresApi
import androidx.core.content.ContextCompat

/**
 * 获取媒体图片
 */
fun requestPermission(
    context: Context,
    permissionLauncher: PermissionLauncher,
    intentLauncher: IntentLauncher,
    permission: Array<String>,
    tip: String,
    agreeAction: (() -> Unit)? = null,
    disAgreeAction: (() -> Unit)? = null
) {

    val permissionFlag =
        permission.all {
            ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
        }
    if (permissionFlag) {
        agreeAction?.invoke()
    } else {
        permissionLauncher.launch(permission) { callback ->
            val isGrantAll = callback.values.all { it }
            if (!isGrantAll) {
                context.alert(tip) {
                    positiveButton("Jump") { dialog ->
                        goToPermissionSettings(context, intentLauncher)
                        dialog.dismiss()
                    }
                    negativeButton("Cancel") { dialog ->
                        dialog.dismiss()
                        disAgreeAction?.invoke()
                    }
                    //禁止取消
                    isCancel(false)
                }
            } else {
                agreeAction?.invoke()
            }
        }
    }
}

//权限设置界面
private fun goToPermissionSettings(context: Context, intentLauncher: IntentLauncher) {
    val intent = appSettingsIntent(context.packageName)
    intentLauncher.launch(intent)
}

/**
 * 应用设置页面意图
 */
fun appSettingsIntent(packageName: String): Intent {
    return Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        .setData(Uri.fromParts("package", packageName, null))
}


//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
fun Context.storePermissionCheck(): Boolean {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {//Android 13以后
        return Environment.isExternalStorageManager()
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {//Android 11以后
        val flag1 = Environment.isExternalStorageManager()
        val flag2 = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }
        return flag1 or flag2
    } else { //Android 11以下,Android 6以上
        return arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }
    }
}

//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(
    permissionLauncher: PermissionLauncher,
    intentLauncher: IntentLauncher,
    disAgreeAction: (() -> Unit)? = null,
    agreeAction: (() -> Unit)? = null,
) {

    //请求读写管理权限
    @SuppressLint("NewApi")
    val requestExternalStorageManager: () -> Unit = {
        if (!Environment.isExternalStorageManager()) {
            val uri = Uri.parse("package:$packageName")
            val intent = settingManageExternalStorage(uri)
            intentLauncher.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, permissionLauncher, intentLauncher,
            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, permissionLauncher, intentLauncher,
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), "Set permission to access external storage",
            agreeAction = {
                //读写权限通过
                agreeAction?.invoke()
            }, disAgreeAction = { disAgreeAction?.invoke() }
        )
    }
}

/**
 * 访问所有文件权限设置界面
 * https://blog.csdn.net/qq_17766199/article/details/115351949
 */
@RequiresApi(Build.VERSION_CODES.R)
fun settingManageExternalStorage(uri: Uri? = null): Intent {
    val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri)
//    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    return intent
}

