package melody.offline.music.util

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.os.SystemClock
import melody.offline.music.App
import melody.offline.music.activity.LaunchActivity

/**
 * 一个处理应用程序生命周期事件并管理启动页显示的类。
 *
 * @param application 应用程序实例。
 */
class AppLifecycleHandler(private val application: Application) :
    Application.ActivityLifecycleCallbacks {

    private var activityReferences = 0
    private var isActivityChangingConfigurations = false
    private var lastPausedTime: Long = 0
    private val intervalTime = 5000L

    init {
        application.registerActivityLifecycleCallbacks(this)
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}

    override fun onActivityStarted(activity: Activity) {
        if (++activityReferences == 1 && !isActivityChangingConfigurations) {
            // 应用进入前台
            val currentTime = SystemClock.elapsedRealtime()
            val isAdShowing = App.app.isAdShowing.get()
            //间隔时间是否满足，当前不是启动页，当前不是广告show
            if (currentTime - lastPausedTime > intervalTime && activity !is LaunchActivity && !isAdShowing) {
                val intent = Intent(activity, LaunchActivity::class.java)
                intent.putExtra(LaunchActivity.FROM_TYPE, 1)
                activity.startActivity(intent)
            }
        }
    }

    override fun onActivityResumed(activity: Activity) {}

    override fun onActivityPaused(activity: Activity) {}

    override fun onActivityStopped(activity: Activity) {
        isActivityChangingConfigurations = activity.isChangingConfigurations
        if (--activityReferences == 0 && !isActivityChangingConfigurations) {
            // 应用进入后台
            lastPausedTime = SystemClock.elapsedRealtime()
        }
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

    override fun onActivityDestroyed(activity: Activity) {}
}
