package com.gh.base

import android.app.Activity
import android.app.Application
import android.content.res.Configuration
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.gh.ad.AdDelegateHelper
import com.gh.common.util.FloatingBackViewManager
import com.gh.common.xapk.XapkInstaller
import com.gh.download.DownloadManager
import com.gh.gamecenter.SingletonWebActivity
import com.gh.gamecenter.SkipActivity
import com.gh.gamecenter.SplashAdActivity
import com.gh.gamecenter.SplashScreenActivity
import com.gh.gamecenter.authorization.AuthorizationActivity
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.provider.IHelpAndFeedbackProvider
import com.gh.gamecenter.common.utils.PackageFlavorHelper
import com.gh.gamecenter.core.provider.IPushProvider
import com.gh.gamecenter.login.utils.QuickLoginHelper
import com.gh.gamecenter.login.view.LoginActivity
import com.gh.gamecenter.va.VCore
import com.gh.vspace.VHelper
import com.halo.assistant.HaloApp
import com.therouter.TheRouter

// TODO：移动到对应的模块
class GlobalActivityLifecycleObserver : Application.ActivityLifecycleCallbacks {
    private var isFromBackgroundToForeground = false // 是否后台回到前台

    override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) {
        if (QuickLoginHelper.isLoginAuthPage(activity)) {
            try {
                val resources = activity.resources
                val config = Configuration(resources.configuration)
                config.fontScale = 1.0f

                // 更新Resources配置
                val metrics = resources.displayMetrics
                metrics.scaledDensity = metrics.density
                resources.updateConfiguration(config, metrics)

            } catch (e: Exception) {
                // 设置字体失败
            }
        }
    }

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

    override fun onActivityStarted(activity: Activity) {
        GlobalActivityManager.currentActivity = activity
        GlobalActivityManager.activityCount++
        if (GlobalActivityManager.activityCount == 1 && isFromBackgroundToForeground) {
            if (AdDelegateHelper.shouldShowStartUpAd(true)
                && !HaloApp.getInstance().isDisableSplashAdTemporarily
                && activity !is SplashScreenActivity
                && activity !is SkipActivity
                && activity !is AuthorizationActivity
                && activity !is SplashAdActivity
                && !isSuggestionActivity(activity)
            ) {
                activity.startActivity(SplashAdActivity.getIntent(activity))
            }
            isFromBackgroundToForeground = false
        }

        if (GlobalActivityManager.activityCount == 1) {
            // 清除桌面角标
            if (activity !is SplashScreenActivity && activity !is AuthorizationActivity) {
                val pushProvider = TheRouter.get(IPushProvider::class.java)
                pushProvider?.cleanBadgeNumber(activity.applicationContext)
            }
        }
        if (QuickLoginHelper.isLoginAuthPage(activity)) {
            QuickLoginHelper.addCustomViewToLoginAuthPage(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
            && !VCore.getInstance().isLaunchActivity(activity)
            && activity !is LoginActivity
            && activity !is SplashScreenActivity
            && activity !is SkipActivity
            && activity !is AuthorizationActivity
        ) {
            VHelper.showFeedbackDialogIfLastSuccessfulLaunchedGameExitUnexpectedly(activity)
        }

        XapkInstaller.updateCurrentInstallStatus()
    }

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

    override fun onActivityStopped(activity: Activity) {
        GlobalActivityManager.activityCount--
        isFromBackgroundToForeground = GlobalActivityManager.activityCount <= 0
    }

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

    override fun onActivityDestroyed(activity: Activity) {
        if (QuickLoginHelper.isLoginAuthPage(activity)) {
            QuickLoginHelper.release()
        }
    }

    private fun isSuggestionActivity(activity: Activity): Boolean {
        val helpAndFeedbackProvider = TheRouter.get(IHelpAndFeedbackProvider::class.java)
        return helpAndFeedbackProvider?.isSuggestionActivity(activity) ?: false
    }

}