package com.base.pdfreaderallpdfreader.ui.splash

import android.content.ContentValues.TAG
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.base.pdfreaderallpdfreader.ads.AdmobHelper.open_ad_loading
import com.base.pdfreaderallpdfreader.bean.ConstObject
import com.base.pdfreaderallpdfreader.utils.AppPreferences
import com.base.pdfreaderallpdfreader.utils.LogEx
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class SplashViewModel : ViewModel() {

    var startJumpJob: Boolean = false
    private var jumpJob: Job? = null

    private var loadingTime = AppPreferences.getInstance().getString(open_ad_loading, "15").toInt()

    /**
     * 超时跳转
     */
    fun startJumpJob(splashActivity: SplashActivity) {
        if (ConstObject.ifAgreePrivacy && startJumpJob) {
            if (jumpJob == null) {
                val startTime = System.currentTimeMillis()
                jumpJob = viewModelScope.launch {
                    LogEx.logDebug(TAG, "open_ad_loading=$loadingTime")
                    delay(loadingTime * 1000L)
                    val endTime = System.currentTimeMillis()
                    LogEx.logDebug(TAG, "超时跳转 time=${endTime - startTime}")
                    splashActivity.jumpNext()
                }
            }
        }
    }

    /**
     * 暂停超时跳转
     */
    fun pauseJumpJob() {
        jumpJob?.cancel()
        jumpJob = null
    }
}