package com.jishisongfu.duobibi.heartbeat

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle

/**
 * 自维护"App 是否在前台"标志,用 ActivityLifecycleCallbacks 计数已启动 Activity 数。
 *
 * 不用 ProcessLifecycleOwner 是为了避免新引入 androidx.lifecycle:lifecycle-process
 * 依赖。计数器算法简单可靠:任意 Activity onStart++、onStop--,>0 即前台。
 *
 * 必须在 [com.jishisongfu.duobibi.DuobibiApplication.onCreate] 调一次 [init]。
 */
object AppForegroundProbe {

    @Volatile
    private var startedCount: Int = 0

    fun init(app: Application) {
        app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityStarted(activity: Activity) { startedCount++ }
            override fun onActivityResumed(activity: Activity) {}
            override fun onActivityPaused(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {
                startedCount = (startedCount - 1).coerceAtLeast(0)
            }
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {}
        })
    }

    @Suppress("UNUSED_PARAMETER")
    fun isInForeground(context: Context): Boolean = startedCount > 0
}
