package com.ym.library.net;

import android.text.TextUtils;


import com.ym.library.utils.RxBus;

import org.apache.poi.hssf.record.formula.functions.Int;

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")) {//重试设备登录和获取用户信息
            RxBus.get().post("refresh_login", "not_login");
        } else if (TextUtils.equals(result.status, "160")) {
            onFailure(null, "160", "请重试");//该异常可以汇报服务端
        } else {
            onFailure(new Exception(result.msg), result.status, result.msg == null?"":result.msg);//该异常可以汇报服务端
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
		onFailure(e, "250", e.getMessage() == null?"":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);
}
