package com.clean.file.b.business.newAdmob

import android.animation.ObjectAnimator
import android.animation.ValueAnimator.INFINITE
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.animation.LinearInterpolator
import com.swiftcleaner.chovey.R
import com.swiftcleaner.chovey.databinding.DialogAdLoadingBinding

object AdDialog {
    fun Context.showAdLoadingDialog(): AlertDialog {
        val binding = DialogAdLoadingBinding.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 = resources.getDimensionPixelOffset(R.dimen.dp_228)
        params?.height = resources.getDimensionPixelOffset(R.dimen.dp_124)
        dialog.window?.attributes = params
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

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

        val textTime = binding.textTime
        var count = 3
        val countDownRunnable = object : Runnable {
            override fun run() {
                if (count > 0) {
                    textTime.text = "($count)"
                    count--
                    Handler(Looper.getMainLooper()).postDelayed(this, 1000)
                } else {
                    dialog.dismiss()
                }
            }
        }
        Handler(Looper.getMainLooper()).postDelayed(countDownRunnable, 0)

        return dialog
    }
}