package com.gh.gamecenter.common.retrofit

import com.gh.gamecenter.common.utils.PackageFlavorHelper
import com.gh.gamecenter.core.utils.ToastUtils
import com.google.gson.JsonSyntaxException
import com.lightgame.utils.Utils
import io.reactivex.functions.BiConsumer

abstract class BiResponse<T> : BiConsumer<T, Throwable> {

    override fun accept(t: T?, throwable: Throwable?) {
        if (t != null) {
            onSuccess(t)
            return
        }

        if (throwable != null) {
            throwable.printStackTrace()
            when (throwable) {
                is Exception -> {
                    showJsonParseException(throwable)
                    onFailure(throwable)
                }
            }
        } else {
            Utils.log("Something serious has happened!")
        }
    }

    abstract fun onSuccess(data: T)

    open fun onFailure(exception: Exception) {
        // 不管是否重写此方法，错误的 stackTrace 都会输出到 Logcat

    }

    private fun showJsonParseException(exception: Exception) {
        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
            if (exception is JsonSyntaxException) {
                ToastUtils.showToast(exception.localizedMessage)
            }
        }
    }

}