package com.gh.gamecenter.pkg

import android.util.Base64
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.entity.PkgConfigEntity
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.core.provider.IPkgProvider
import com.gh.gamecenter.core.utils.SPUtils
import java.nio.charset.Charset

object PkgHelper {

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

    private var mActivateRatioFromInternet = 0

    private val mPkgProvider by lazy {
        ARouter.getInstance().build(RouteConsts.provider.pkg).navigation() as? IPkgProvider<PkgConfigEntity>
    }

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

    fun getPkgConfig(isFromHomeTopTab: Boolean): PkgConfigEntity.PkgLinkEntity? {
        if (mPkgConfigLink == null
            && !SPUtils.getBoolean(SP_PKG_CONFIG_IS_USED, false)
            && BuildConfig.FIRST_LAUNCH.isNotEmpty()
        ) {

            mPkgConfigLink =
                String(Base64.decode(BuildConfig.FIRST_LAUNCH, Base64.DEFAULT), Charset.defaultCharset()).toObject()

            return if (isFromHomeTopTab) {
                if (mPkgConfigLink?.shouldStayAtHomePage != true && mPkgConfigLink?.homeBottomTab == "home") {
                    markConfigUsed()
                    mPkgConfigLink
                } else {
                    null
                }
            } else {
                mPkgConfigLink
            }
        }

        return mPkgConfigLink
    }

    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) {
            mPkgConfigLink = it.data?.link
            mActivateRatioFromInternet = it.data?.activateRatio ?: 0
        }

    }

}