package com.gh.gamecenter.pkg

import com.therouter.TheRouter
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.entity.PkgConfigEntity
import com.gh.gamecenter.core.provider.IPkgProvider
import com.gh.gamecenter.core.utils.SPUtils

object PkgHelper {
    private var mTempPkgConfigEntity: PkgConfigEntity.PkgLinkEntity? = null // 临时的特殊包配置副本，仅供 debug 使用

    private var mPkgConfigLink: PkgConfigEntity.PkgLinkEntity? = null
    private const val SP_PKG_CONFIG_IS_USED = "pkg_config_is_used"

    private var mActivateRatioFromInternet = 0
    private var mCoreEventGameCategory: String? = null

    private val mPkgProvider by lazy {
        TheRouter.get(IPkgProvider::class.java)
    }

    /**
     * 获取激活比例
     */
    fun getActivateRatio(): Int {
        return if (mActivateRatioFromInternet > 0) {
            mActivateRatioFromInternet
        } else {
            BuildConfig.ACTIVATE_REPORTING_RATIO
        }
    }

    /**
     * 获取预设的游戏类型上报关键事件
     */
    fun getCoreEventGameCategory(): String? {
        return mCoreEventGameCategory ?: BuildConfig.CORE_EVENT_GAME_CATEGORY
    }

    fun markConfigUsed() {
        mPkgConfigLink = null
        SPUtils.setBoolean(SP_PKG_CONFIG_IS_USED, true)
    }

    /**
     * 从接口获取特殊包配置
     */
    fun requestPkgConfig(configId: String) {
        if (SPUtils.getBoolean(SP_PKG_CONFIG_IS_USED, false)) return

        mPkgProvider?.requestPkgConfig(configId) {
            val pkgConfig = it as? PkgConfigEntity ?: return@requestPkgConfig

            mPkgConfigLink = pkgConfig.link
            mActivateRatioFromInternet = pkgConfig.activateRatio ?: 0
            mCoreEventGameCategory = pkgConfig.coreEventGameCategory
        }
    }

    /**
     * 获取特殊包配置的副本，仅 debug 使用
     */
    fun getTempPkgConfigLink(): PkgConfigEntity.PkgLinkEntity? {
        return mTempPkgConfigEntity
    }

}