package com.base.appzxhy.ui.dialog

import android.app.Activity
import android.view.Gravity
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.graphics.toColorInt
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseActivity
import com.base.appzxhy.base.jumpAction
import com.base.appzxhy.databinding.DialogStorage2Binding
import com.base.appzxhy.utils.PermissionUtils.checkStorePermission
import com.base.appzxhy.utils.PermissionUtils.requestStoragePermission
import com.base.appzxhy.utils.SpannableUtils.highlightText


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 = DialogStorage2Binding.inflate(LayoutInflater.from(activity))

    var action: (() -> Unit)? = null
    var actionEd: Boolean = false

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

        dialog.show()

        val params = dialog.window?.attributes
//        params?.width = activity.resources.getDimensionPixelSize(R.dimen.dp_316)
        params?.width = ConstraintLayout.LayoutParams.MATCH_PARENT
        params?.height = ConstraintLayout.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 =
            highlightText(activity.getString(R.string.storage_permission_content, appName), appName, "#46B7D6".toColorInt())

//        binding.lottieAnimationView.let {
//            it.imageAssetsFolder = "permission_sc/images"
//            it.setAnimation("permission_sc/data.json")
//            it.loop(true)
//            it.playAnimation()
//        }

//        binding.tvDeny.setOnClickListener {
//            dialog.dismiss()
//        }
        binding.tvOpenSettings.setOnClickListener {
            actionEd = true
            dialog.dismiss()
            action?.invoke()
        }
    }


}