package com.zxhy.fastfilemanagerpro.kokotools.permission

import android.content.Context
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.zxhy.fastfilemanagerpro.kokotools.ActivityLauncher
import com.zxhy.fastfilemanagerpro.kokotools.IntentEx.goToPermissionSettings

object PermissionEx {
    fun requestPermission(
        context: Context,
        activityLauncher: ActivityLauncher,
        permission: Array<String>,
        title: String = "title",
        message: String = "message",
        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(title = title, message = message,
                        positiveButton = {
                            goToPermissionSettings(context, activityLauncher)
                        },
                        negativeButton = {
                            disAgreeAction?.invoke()
                        })
                } else {
                    agreeAction?.invoke()
                }
            }
        }
    }

    fun Context.alert(
        title: String = "",
        message: String,
        positiveButtonText: String = "Jump",
        positiveButton: (() -> Unit)? = null,
        negativeButtonText: String = "Cancel",
        negativeButton: (() -> Unit)? = null,
    ) {
        val builder = MaterialAlertDialogBuilder(this)
        builder.setNegativeButton(negativeButtonText) { dialog, _ ->
            dialog.dismiss()
            negativeButton?.invoke()
        }
        builder.setPositiveButton(positiveButtonText) { dialog, _ ->
            dialog.dismiss()
            positiveButton?.invoke()
        }
        val dialog = builder.create()
        dialog.setCanceledOnTouchOutside(false)
//        dialog.setTitle(title)
        dialog.setMessage(message)
        dialog.show()
    }
}
