package com.tgv.malware.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.tgv.malware.R
import com.tgv.malware.base.BaseActivity
import com.tgv.malware.base.jumpAction
import com.tgv.malware.databinding.DialogStorageBinding
import com.tgv.malware.utils.PermissionUtils.checkStorePermission
import com.tgv.malware.utils.PermissionUtils.requestStoragePermission
import com.tgv.malware.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 = DialogStorageBinding.inflate(LayoutInflater.from(activity))

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

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

        dialog.show()

        val params = dialog.window?.attributes
        params?.width = activity.resources.getDimensionPixelSize(R.dimen.dp_316)
        params?.height = ConstraintLayout.LayoutParams.WRAP_CONTENT
        params?.gravity = Gravity.CENTER
        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, "#2DD29E".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.tvAllow.setOnClickListener {
            dialog.dismiss()
            action?.invoke()
        }
    }


}