package com.base.appzxhy.business.ads

import android.animation.ObjectAnimator
import android.animation.ValueAnimator.INFINITE
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.animation.LinearInterpolator
import android.widget.TextView
import com.base.appzxhy.R
import com.base.appzxhy.databinding.DialogAdCountdownBinding


object AdCountDownDialog {

    private val TAG = "AdCountDownDialog"

    fun Context.showAdCountDownDialog(): AlertDialog {
        val binding = DialogAdCountdownBinding.inflate(LayoutInflater.from(this))
        val dialog = AlertDialog.Builder(this).create()
        dialog.setView(binding.root)
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)

        dialog.show()
        val params = dialog.window?.attributes
//        params?.width = LinearLayout.LayoutParams.WRAP_CONTENT
        params?.width = resources.getDimensionPixelSize(R.dimen.dp_300)
//        params?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        dialog.window?.attributes = params
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        // 创建一个旋转动画
        val rotateAnimator = ObjectAnimator.ofFloat(binding.ivYuan, "rotation", 0f, -360f)
        rotateAnimator.setDuration(1000) // 设置动画持续时间为1000毫秒
        rotateAnimator.repeatCount = INFINITE
        rotateAnimator.interpolator = LinearInterpolator() // 设置插值器为线性插值
        rotateAnimator.start()

        return dialog
    }


    fun createUICountdownTimer(dialog: Dialog?, onFinish: () -> Unit) {

        val tvCountdown = dialog?.findViewById<TextView>(R.id.tvCountdown)

        val countDownTimer = object : CountDownTimer(4000, 1000) {
            @SuppressLint("SetTextI18n")
            override fun onTick(millisUntilFinished: Long) {
                val s = millisUntilFinished / 1000
                tvCountdown?.text = "Ads are about to be shown(${s}s)"
            }

            override fun onFinish() {
                kotlin.runCatching {
                    dialog?.dismiss()
                }
                onFinish.invoke()
            }
        }
        countDownTimer.start()
    }
}