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.base.ApiEmptyResponse
import com.remax.visualnovel.entity.response.base.ApiFailedResponse
import com.remax.visualnovel.entity.response.base.ApiSuccessResponse
import com.remax.visualnovel.entity.response.base.Response
import com.remax.visualnovel.extension.toast
import com.remax.visualnovel.manager.login.LoginManager
import timber.log.Timber

open class BaseRepository {

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

    private suspend fun <T> execute(block: suspend () -> Response<T>): Response<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(errorMsg = errorMsg)
    }

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

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

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

            else -> {
                ApiFailedResponse(response.errorCode, response.errorMsg)
            }
        }
    }

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

}