package com.gh.gamecenter.login.interceptor

import android.text.TextUtils
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.NetworkUtils
import com.gh.gamecenter.core.HaloApp
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.utils.QuickLoginHelper
import com.lightgame.utils.Utils
import com.therouter.router.RouteItem
import com.therouter.router.getUrlWithParams
import com.therouter.router.interceptor.RouterReplaceInterceptor
import com.therouter.router.matchRouteMap

class LoginInterceptor : RouterReplaceInterceptor() {

    override fun replace(routeItem: RouteItem?): RouteItem? {
        val url = routeItem?.getUrlWithParams()
        val extra = routeItem?.getExtras()

        Utils.log(TAG, "loginInterceptor about to intercept $url")

        // 如果不需要登录，或者已经登录，直接返回 routeItem
        if (extra?.getString(RouteConsts.QueryParams.REQUIRE_LOGIN) != "true"
            || !TextUtils.isEmpty(UserManager.getInstance().getToken())
        ) {
            return routeItem
        } else {
            val currentActivity = CurrentActivityHolder.getCurrentActivity()

            if (currentActivity != null
                && NetworkUtils.isQuickLoginEnabled(HaloApp.getInstance())) {
                QuickLoginHelper.startLogin(currentActivity, "浏览器", routeItem.getUrlWithParams())
                return null
            } else {
                val target = matchRouteMap(RouteConsts.activity.loginActivity)
                target?.description = routeItem.getUrlWithParams()
                return target
            }
        }
    }

    companion object {
        private const val TAG = "LoginInterceptor"
    }

}