package com.atmob.keyboard_android.util.error

import com.atmob.keyboard_android.component.ComponentMediator
import com.atmob.keyboard_android.component.root.IKeyboardRootComponent
import com.atmob.keyboard_android.enums.ServerErrorCode
import com.atmob.keyboard_android.util.ToastUtil
import com.atmob.keyboard_android.util.UserInfoHelper

/**
 * 错误处理类
 */
class ErrorHandler private constructor() {
    companion object {
        /**
         * 处理错误
         *
         * @param errorCode 错误码
         * @param errorMessage 错误消息
         */
        fun handleError(errorCode: Int, errorMessage: String?, needToast: Boolean = true) {
            val keyboardRootComponent =
                ComponentMediator.findComponent(IKeyboardRootComponent::class.java)

            // 需要VIP
            if (ServerErrorCode.NEED_VIP.code == errorCode) {
                UserInfoHelper.isLogin { hasLogin ->
                    // 已登录，但没有VIP，跳去VIP页
                    if (hasLogin) {
                        keyboardRootComponent?.switchVipPage()
                    } else {
                        // 未登录，跳去登录页
                        keyboardRootComponent?.switchLoginPage()
                    }
                }
            } else if (ServerErrorCode.NO_LOGIN.code == errorCode) {
                // 未登录
                keyboardRootComponent?.switchLoginPage()
            }

            if (needToast) {
                ToastUtil.showToast(errorMessage)
            }
        }
    }
}