package com.gh.gamecenter.common.base

import android.app.Activity
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.entity.PageEntity
import com.gh.gamecenter.common.utils.getUniqueId
import java.lang.ref.WeakReference
import java.util.*

object GlobalActivityManager {
    private var mCurrentActivityWeakRef: WeakReference<Activity>? = null

    var currentActivity: Activity?
        get() = mCurrentActivityWeakRef?.get()
        set(activity) {
            mCurrentActivityWeakRef = WeakReference<Activity>(activity)
        }

    var activityCount: Int = 0

    val pageStack = Stack<PageEntity>()

    @JvmStatic
    fun getCurrentPageEntity(): PageEntity = if (pageStack.isNotEmpty()) {
        pageStack.peek()
    } else {
        PageEntity()
    }

    @JvmStatic
    fun isAppForeground(): Boolean = activityCount > 0

    @JvmStatic
    fun getLastPageEntity(): PageEntity = if (pageStack.size >= 2) {
        pageStack[pageStack.size - 2]
    } else {
        PageEntity()
    }

    fun updatePageBusinessId(activity: Activity) {
        if (activity is BaseActivity && pageStack.isNotEmpty() && pageStack.peek().pageId == activity.getUniqueId()) {
            pageStack.peek().pageBusinessId = activity.getBusinessId().first
        }
    }
}