package com.remax.visualnovel.repository.api.base


import com.remax.visualnovel.R
import com.remax.visualnovel.app.base.app.CommonApplicationProxy
import com.remax.visualnovel.constant.StatusCode
import com.remax.visualnovel.entity.response.basenew.ApiEmptyResponse
import com.remax.visualnovel.entity.response.basenew.ApiFailedResponse
import com.remax.visualnovel.entity.response.basenew.ApiSuccessResponse
import com.remax.visualnovel.entity.response.basenew.ResponseNew
import com.remax.visualnovel.extension.toast
import com.remax.visualnovel.manager.login.LoginManager
import timber.log.Timber

open class BaseRepositoryNew {

    /**
     * 如果不需要检查登录，那么在未登录的情况下 直接返回Success
     * @param checkLogin  检查登录，默认都需要检查
     */
    suspend fun <T> executeHttp(checkLogin: Boolean = true, block: suspend () -> ResponseNew<T>): ResponseNew<T> {
        return if (!checkLogin) {
            if (LoginManager.isLogin) {
                execute(block)
            } else {
                ApiSuccessResponse()
            }
        } else {
            execute(block)
        }
    }

    private suspend fun <T> execute(block: suspend () -> ResponseNew<T>): ResponseNew<T> {
        return try {
            val data = block.invoke()
            handleHttpOk(data)
        } catch (e: Exception) {
            handleHttpError(e)
        }
    }

    /**
     * 非后台返回错误，捕获到的异常
     */
    private fun <T> handleHttpError(e: Throwable): ApiFailedResponse<T> {
        Timber.e("responseAsync error -> ${e.localizedMessage}")
        val errorMsg = CommonApplicationProxy.application.getString(R.string.your_network_error)
        return ApiFailedResponse(message = errorMsg)
    }

    /**
     * http返回200，还要判断后端业务层isSuccess
     */
    private fun <T> handleHttpOk(response: ResponseNew<T>): ResponseNew<T> {
        return when {
            //后端业务正常
            response.isOk -> {
                getHttpSuccessResponse(response)
            }

            //登录超时
            response.code == /*StatusCode.TOKEN_EXPIRED.code*/403 -> {
                CommonApplicationProxy.application.toast(response.message)
                LoginManager.logout()
                ApiFailedResponse(response.code, response.message)
            }

            //余额不足
            response.code == /*StatusCode.INSUFFICIENT_BALANCE.code*/ 610 -> {
                /*WalletManager.refreshWallet()
                WalletManager.showChargeDialog()*/
                ApiFailedResponse(response.code, response.message)
            }

            else -> {
                ApiFailedResponse(response.code, response.message)
            }
        }
    }

    /**
     * 成功和数据为空的处理
     */
    private fun <T> getHttpSuccessResponse(response: ResponseNew<T>): ResponseNew<T> {
        val data = response.data
        return if (data == null) {
            ApiEmptyResponse()
        } else {
            ApiSuccessResponse(data)
        }
    }

}