package com.gh.gamecenter.common.retrofit;

import androidx.annotation.Nullable;

import com.gh.gamecenter.common.BuildConfig;
import com.gh.gamecenter.common.utils.PackageFlavorHelper;
import com.gh.gamecenter.core.utils.AppDebugConfig;
import com.gh.gamecenter.core.utils.ToastUtils;
import com.google.gson.JsonSyntaxException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * Created by LGT on 2016/11/7.
 * Response
 */
public class Response<T> implements Observer<T> {

    @Deprecated
    @Override
    public void onError(Throwable e) {
        if (AppDebugConfig.IS_DEBUG) {
            AppDebugConfig.logMethodWithParams(this, e);
        }

        if (e instanceof NullPointerException && "Null is not a valid element".equals(e.getMessage())) {
            onResponse(null);
            return;
        }

        ApiResponse<T> e1 = new ApiResponse<>();

        //上面的null，导致当retrofit发生其他类型错误时，又刚好想打印e的输出，则发生NPE，增加throwable重载，只做传递 by CsHeng 2017.06.14
        if (e instanceof HttpException) {
            e1.setHttpException((HttpException) e);
            onFailure((HttpException) e);
        } else {
            e1.setThrowable(e);
            onFailure(null);
        }

        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
            if (e instanceof JsonSyntaxException) {
                ToastUtils.showToast(e.getLocalizedMessage());
            }
        }

        onApiFailure(e1);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T response) {
        // DEBUG 模式就让它崩
        if (BuildConfig.DEBUG) {
            onResponse(response);
        } else {
            try {
                onResponse(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void onResponse(@Nullable T response) {

    }

    public void onFailure(@Nullable HttpException e) {

    }

    public void onApiFailure(ApiResponse<T> e) {

    }

}
