package com.simplecleaner.app.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.simplecleaner.app.R
import com.simplecleaner.app.base.BaseActivity
import com.simplecleaner.app.base.jumpAction
import com.simplecleaner.app.databinding.DialogStorage2Binding
import com.simplecleaner.app.utils.PermissionUtils.checkStorePermission
import com.simplecleaner.app.utils.PermissionUtils.requestStoragePermission
import com.simplecleaner.app.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, "#06D16C".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()
        }
    }


}