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

import com.ama.core.architecture.R
import com.ama.core.architecture.basebean.ApiEmptyResponse
import com.ama.core.architecture.basebean.ApiFailedResponse
import com.ama.core.architecture.basebean.ApiSuccessResponse
import com.ama.core.architecture.basebean.ResponseNew


open class BaseRepositoryNew {

    suspend fun <T> executeHttp(checkLogin: Boolean = true, block: suspend () -> ResponseNew<T>): ResponseNew<T> {
        return execute(block)

        /*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> {
        val errorMsg = e.toString()
        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)
        }
    }

}