package com.zxhy.solarmasterace.permission

import android.content.Context
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import com.zxhy.solarmasterace.dialog.alert
import com.zxhy.solarmasterace.quicktools.ActivityLauncher
import com.zxhy.solarmasterace.quicktools.goToPermissionSettings

fun requestPermission(
    context: Context,
    activityLauncher: ActivityLauncher,
    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 {
        activityLauncher.launch(permission) { callback ->
            val isGrantAll = callback.values.all { it }
            if (!isGrantAll) {
                context.alert(tip) {
                    positiveButton("Jump") { dialog ->
                        goToPermissionSettings(context, activityLauncher)
                        dialog.dismiss()
                    }
                    negativeButton("Cancel") { dialog ->
                        dialog.dismiss()
                        disAgreeAction?.invoke()
                    }
                    //禁止取消
                    isCancel(false)
                }
            } else {
                agreeAction?.invoke()
            }
        }
    }
}