package com.simplecleaner.app.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.simplecleaner.app.R
import com.simplecleaner.app.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) {
        if (dialog == null) {
            onFinish.invoke()
            return
        }

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

        val countDownTimer = object : CountDownTimer(2000, 1000) {
            @SuppressLint("SetTextI18n")
            override fun onTick(millisUntilFinished: Long) {
                val s = millisUntilFinished / 1000
                tvCountdown?.text = tvCountdown.context.getString(R.string.ads_are_about_to_be_shown_s, s)
            }

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