package com.remax.visualnovel.app

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.remax.visualnovel.app.initializer.utils.FirebaseHelper
import com.remax.visualnovel.app.viewmodel.AppGlobalViewModel


/**
 * Created by HJW on 2022/9/21
 * 监听整个app生命周期
 */
object ProcessLifecycleObserver : DefaultLifecycleObserver {

    var isOnResume = false
    private var refreshFirebaseTokenTime = 0L

    private var appGlobalViewModel: AppGlobalViewModel? = null

    fun setAppGlobalViewModel(appGlobalViewModel: AppGlobalViewModel) {
        ProcessLifecycleObserver.appGlobalViewModel = appGlobalViewModel
    }

    /**
     * APP在前台回调
     */
    override fun onResume(owner: LifecycleOwner) {
        isOnResume = true
        val currTime = System.currentTimeMillis()
        if (refreshFirebaseTokenTime != 0L && currTime - refreshFirebaseTokenTime > 60 * 1000) {
            refreshFirebaseTokenTime = currTime
            FirebaseHelper.getToken {
                appGlobalViewModel?.updateTerminal(it)
            }
        }

    }

    /**
     * APP进入后台回调
     */
    override fun onPause(owner: LifecycleOwner) {
        isOnResume = false
    }
}