package com.gh.gamecenter.common.base

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.PageEntity
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.getUniqueId
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.lightgame.utils.AppManager
import org.greenrobot.eventbus.EventBus

class GlobalActivityLifecycleObserver : Application.ActivityLifecycleCallbacks {

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        if (GlobalActivityManager.currentActivity?.javaClass?.simpleName == "MainActivity") {
            EventBus.getDefault().post(EBReuse(Constants.FINISH_HOME_PUSH))
        }

        AppManager.getInstance().addActivity(activity)

        if (activity is BaseActivity) {
            GlobalActivityManager.pageStack.push(
                PageEntity(
                    pageId = activity.getUniqueId(),
                    pageName = activity::class.java.simpleName
                )
            )
        }
    }

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

    override fun onActivityResumed(activity: Activity) {
        CurrentActivityHolder.activitySet.add(activity)
    }

    override fun onActivityPaused(activity: Activity) {
        CurrentActivityHolder.activitySet.remove(activity)
        if (activity.isFinishing) {
            AppManager.getInstance().finishActivity(activity)
        }
    }

    override fun onActivityStopped(activity: Activity) {

    }

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

    }

    override fun onActivityDestroyed(activity: Activity) {
        AppManager.getInstance().removeActivityFromStack(activity)

        if (activity is BaseActivity) {
            if (GlobalActivityManager.pageStack.peek().pageId == activity.getUniqueId()) {
                GlobalActivityManager.pageStack.pop()
            } else {
                var position = -1
                GlobalActivityManager.pageStack.forEachIndexed { index, pageEntity ->
                    if (pageEntity.pageId == activity.getUniqueId()) {
                        position = index
                    }
                }
                if (position != -1) {
                    GlobalActivityManager.pageStack.removeAt(position)
                }
            }
        }
    }
}