package com.base.appzxhy.ui.dialog

import android.animation.ValueAnimator
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintLayout
import com.base.appzxhy.R
import com.base.appzxhy.bean.config.AdConfigBean
import com.base.appzxhy.business.ads.AdsMgr
import com.base.appzxhy.databinding.DialogAppExitBinding

class AppExitDialog(val activity: Activity) {

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

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

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

        dialog.show()

        val params = dialog.window?.attributes
//        params?.width = ConstraintLayout.LayoutParams.MATCH_PARENT
        params?.width = activity.resources.getDimensionPixelSize(R.dimen.dp_295)
        params?.height = ConstraintLayout.LayoutParams.WRAP_CONTENT
//        params?.gravity = Gravity.BOTTOM
        dialog.window?.attributes = params
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        val exit = activity.getString(R.string.exit)
        ValueAnimator.ofInt(0, 3).apply {
            duration = 3000
            interpolator = LinearInterpolator()
            addUpdateListener { animation ->
                val value = animation.animatedValue as Int
                binding.tvExit.text = if (value < 3) "$exit (${3 - value})" else exit
                binding.tvExit.isEnabled = value == 3
            }
        }.start()
        AdsMgr.showNative(binding.flAd, R.layout.layout_admob_native_custom)
        if (!AdConfigBean.adsConfigBean.isAdShow) {
            binding.fl.visibility = View.GONE
        }

        binding.ivCancel.setOnClickListener {
            dialog.dismiss()
        }
        binding.tvExit.setOnClickListener {
            activity.finish()
        }
        binding.tvCleanNow.setOnClickListener {
            dialog.dismiss()
            action?.invoke()
        }
    }
}