package com.atmob.keyboard_android.component.base.interceptor

import com.atmob.keyboard_android.component.ComponentConstant
import com.atmob.keyboard_android.component.annotation.Component
import com.atmob.keyboard_android.component.base.IBusinessComponent
import com.atmob.keyboard_android.component.base.IUIComponent
import com.atmob.keyboard_android.component.exception.NoLoginException
import com.atmob.keyboard_android.util.LogUtil
import com.atmob.keyboard_android.util.UserInfoHelper

/**
 * 登录路由拦截器
 */
class LoginRouteInterceptor : IRouteInterceptor {
    override fun onInit() {
    }

    override fun onUnInit() {
    }

    override fun doProcess(
        targetComponent: IUIComponent,
        callback: InterceptorCallback
    ) {
        val componentAnnotation = targetComponent.javaClass.getAnnotation(Component::class.java)
        if (componentAnnotation != null) {
            // 路由白名单，则直接放行
            val routePath = componentAnnotation.route
            if (ComponentConstant.ROUTE_WHITE_LIST.contains(routePath)) {
                callback.onContinue()
                return
            }
        }
        if (targetComponent is IBusinessComponent) {
            // 判断组件是否需要登录才能路由，如果需要登录，则检查登录状态
            if (targetComponent.isNeedLogin()) {
                UserInfoHelper.checkLogin(nextAction = {
                    LogUtil.d("LoginRouteInterceptor => ${targetComponent.javaClass.name} => 已登录，放行")
                    // 已登录，放行
                    callback.onContinue()
                }, noLoginCallback = {
                    LogUtil.d("LoginRouteInterceptor => ${targetComponent.javaClass.name} => 未登录，拦截，并跳转到登录页")
                    // 未登录，拦截路由
                    callback.onInterrupt(NoLoginException())
                })
            } else {
                LogUtil.d("LoginRouteInterceptor => ${targetComponent.javaClass.name} => 不需要登录，直接放行")
                // 不需要登录，直接放行
                callback.onContinue()
            }
        } else {
            // 非业务组件，放行
            callback.onContinue()
        }
    }
}