package com.abbidot.tracker.vm

import android.os.CountDownTimer
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

/**
 *Created  by .yzq on 2022/7/18/018.
 * @link
 * @description: 倒计时
 */
class CountDownTimerViewModel : ViewModel() {
    val mCountDowningLiveData = MutableLiveData<Long>()
    val mCountDownEndLiveData = MutableLiveData<Long>()
    private var mCountDownTimer: CountDownTimer? = null

    //是否开始倒计时
    var isStartCountDown = false

    /**
     * @param second 秒
     * 倒计时
     */
    fun startCountDown(second: Long, countDownInterval: Long = 1) {
        stopCountDown()
        mCountDownTimer = object : CountDownTimer(second * 1000, countDownInterval * 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                val time = millisUntilFinished / 1000
                isStartCountDown = true
                mCountDowningLiveData.value = time
            }

            override fun onFinish() {
                isStartCountDown = false
                mCountDownEndLiveData.value = 0L
            }
        }.start()
    }

    fun stopCountDown() {
        isStartCountDown = false
        mCountDownTimer?.cancel()
    }

    override fun onCleared() {
        super.onCleared()
        stopCountDown()
    }
}