package com.base.appzxhy.ui.start

import android.os.CountDownTimer
import androidx.lifecycle.ViewModel
import com.base.appzxhy.bean.config.AdConfigBean

class StartViewModel : ViewModel() {

    var jumpNext: (() -> Unit)? = null
    var onTick: ((sLong: Long, total: Long, percent: Int) -> Unit)? = null
    private val openAdLoading = AdConfigBean.adsConfigBean.openAdLoading * 1000L
    private var countdownTimer: CountDownTimer? = null

    fun startJumpCountdown() {
        cancelJumpCountDown()
        countdownTimer = createNewCountdownTimer()
        countdownTimer?.start()
    }

    fun cancelJumpCountDown() {
        countdownTimer?.cancel()
        onTick?.invoke(0, openAdLoading, 0)
    }

    private fun createNewCountdownTimer(): CountDownTimer {
        return object : CountDownTimer(openAdLoading, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val progress = (openAdLoading - millisUntilFinished)
                val percent = (progress * 100 / openAdLoading).toInt()
                onTick?.invoke(progress, openAdLoading, percent)
            }

            override fun onFinish() {
                onTick?.invoke(openAdLoading, openAdLoading, 100)
                jumpNext?.invoke()
                jumpNext = null
            }
        }
    }


}