package com.base.appzxhy.ui.dialog

import android.app.Activity
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseActivity
import com.base.appzxhy.base.jumpAction
import com.base.appzxhy.databinding.DialogStorageBinding
import com.base.appzxhy.utils.PermissionUtils.checkStorePermission
import com.base.appzxhy.utils.PermissionUtils.requestStoragePermission


fun Activity.permissionStorageJump(key: String) {

    if (this !is BaseActivity<*>) {
        throw Exception("")
    }

    if (this.checkStorePermission()) {
        jumpAction(key)
    } else {
        val dialog = StoragePermissionDialog(this)
        dialog.action = {
            requestStoragePermission(launcher) {
                if (it) {
                    jumpAction(key)
                }
            }
        }
        dialog.showDialog()
    }
}


class StoragePermissionDialog(
    val activity: Activity
) {

    val dialog = AlertDialog.Builder(activity).create()
    val binding = DialogStorageBinding.inflate(LayoutInflater.from(activity))

    var action: (() -> Unit)? = null

    fun showDialog() {
        dialog.setView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        dialog.show()

        val params = dialog.window?.attributes
        params?.width = LinearLayout.LayoutParams.MATCH_PARENT
        params?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        params?.gravity = Gravity.BOTTOM
        dialog.window?.attributes = params
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        val appName = activity.getString(R.string.app_name)
        binding.tvContent.text = activity.getString(R.string.storage_permission_content, appName)

        binding.tvOpenSettings.setOnClickListener {
            dialog.dismiss()
            action?.invoke()
        }
    }


}