package com.gh.base

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.gh.common.util.FloatingBackViewManager
import com.gh.download.DownloadManager
import com.gh.gamecenter.SingletonWebActivity
import com.gh.gamecenter.SkipActivity
import com.gh.gamecenter.SplashScreenActivity
import com.gh.gamecenter.authorization.AuthorizationActivity
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.utils.PackageFlavorHelper
import com.gh.vspace.VHelper
import com.halo.assistant.HaloApp

// TODO：移动到对应的模块
class GlobalActivityLifecycleObserver : Application.ActivityLifecycleCallbacks {

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

    override fun onActivityStarted(activity: Activity) {
        GlobalActivityManager.currentActivity = activity
    }

    override fun onActivityResumed(activity: Activity) {
        // 判断是否需要显示或隐藏返回小浮窗
        if (FloatingBackViewManager.getType().isNotEmpty()) {
            if (activity is SingletonWebActivity
                && FloatingBackViewManager.getType() == FloatingBackViewManager.TYPE_ACTIVITY
            ) {
                FloatingBackViewManager.disableBackView()
            } else {
                FloatingBackViewManager.showBackView(activity)
            }
        }

        if (HaloApp.isUserAcceptPrivacyPolicy(activity)) {
            // FIXME 这里应该只是部分Activity需要
            try {
                // 初始化gameMap
                if (activity !is SplashScreenActivity) {
                    DownloadManager.getInstance().initGameMap()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        if (PackageFlavorHelper.IS_TEST_FLAVOR && activity is AppCompatActivity) {
            DarkModeSwitchHelper.showDarkModeSwitchFloatingView(activity)
        }

        if (activity is AppCompatActivity
            && activity !is SplashScreenActivity
            && activity !is SkipActivity
            && activity !is AuthorizationActivity
        ) {
            VHelper.showFeedbackDialogIfLastSuccessfulLaunchedGameExitUnexpectedly(activity)
        }
    }

    override fun onActivityPaused(activity: Activity) {
        FloatingBackViewManager.dismissBackView()
        if (PackageFlavorHelper.IS_TEST_FLAVOR && activity is AppCompatActivity) {
            DarkModeSwitchHelper.dismissDarkModeSwitchFloatingView()
        }
    }

    override fun onActivityStopped(activity: Activity) {
        // do nothing
    }

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

    override fun onActivityDestroyed(activity: Activity) {
        // do nothing
    }

}