package com.zxhy.hfilemanagermaster.permission

import android.Manifest
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.content.ContextCompat

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

    val request: () -> Unit = {
        val permissionFlag =
            permission.all {
                ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
            }
        if (permissionFlag) {
            flag = true
        } else {
            permissionLauncher.launch(permission) { callback ->
                val isGrantAll = callback.values.all { it }
                if (!isGrantAll) {
                    context.alert(tip) {
                        positiveButton("跳转") { dialog ->
                            goToPermissionSettings(context, intentLauncher)
                            dialog.dismiss()
                        }
                        negativeButton("取消") { dialog ->
                            dialog.dismiss()
                        }
                        //禁止取消
                        isCancel(false)
                    }
                } else {
                    agreeAction?.invoke()
                }
            }
        }
//        Toast.makeText(context, "不会等待回调", Toast.LENGTH_SHORT).show()
    }

    if (permission.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        && permission.contains(Manifest.permission.READ_EXTERNAL_STORAGE)
    ) {
        val managerFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            false
        }
        if (managerFlag) {
            return true
        } else {
            request()
        }
    } else {
        request()
    }
    return flag
}

//权限设置界面
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))
}


