package com.dumpster.cleaner.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.dumpster.cleaner.R
import com.dumpster.cleaner.base.BaseActivity
import com.dumpster.cleaner.base.jumpAction
import com.dumpster.cleaner.databinding.DialogStorageBinding
import com.dumpster.cleaner.utils.PermissionUtils.checkStorePermission
import com.dumpster.cleaner.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()
        }
    }


}