package com.zx.ad.modulecommon.net;

import android.text.TextUtils;

import io.reactivex.Observer;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T> implements Observer<Response<T>> {

    private Disposable disposable;

    @Override
    public void onNext(@NonNull Response<T> result) {
        if (TextUtils.equals(result.status, "200")) {
            if (result.result != null) {
                onSuccess(result.result.data);
            } else {
                onSuccess(null);
            }
        } else if (TextUtils.equals(result.status, "101")) {
        } else if (TextUtils.equals(result.status, "160")) {
            onFailure(null, "160", "请重试");//该异常可以汇报服务端
        } else {
            onFailure(new Exception(result.msg), result.status, result.msg);//该异常可以汇报服务端
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
//        if(e.getMessage().contains("403")){//
////            NetConfig.setBase_Url(NetConfig.Environment.DEV);
//            AdPreference.saveEvnvironment(NetConfig.Environment.DEV.toString());
//            NetConfig.setBase_Url(NetConfig.Environment.DEV);
//            restartApp();
//        }
        onFailure(e, "250", e.getMessage());//该异常可以汇报服务端
    }

    @Override
    public void onComplete() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        disposable = d;
    }

    public abstract void onSuccess(T result);

    public abstract void onFailure(Throwable e, String code, String errorMsg);
}
