package com.zhaohaoting.framework.requset.rxjava_retrofit;

import com.google.gson.JsonSyntaxException;
import com.zhaohaoting.framework.abs.entity.ResultEntity;
import com.zhaohaoting.framework.utils.Logger;
import com.zhaohaoting.framework.utils.observer.ObserverManager;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.FlowableSubscriber;

/**
 * Created by Administrator on 2018/5/21.
 */

public abstract class RxResultSubscriber<DATA, BASE_DATA extends ResultEntity<DATA>> implements FlowableSubscriber<BASE_DATA> {

    public static final int FAILURE = -1;//失败
    protected static final int LOCAL_FAILURE = -1000;//本地错误
    public static final int REQUEST_SUCCESS = 0;//请求成功
    public static final int NEED_LOGIN = 6666;//需要从新登录
    public static final String OBSERVER_REQUEST_ERROR = "OBSERVER_REQUEST_ERROR";//

    @Override
    public void onNext(BASE_DATA base_data) {
        if (base_data.getError() == REQUEST_SUCCESS) {
            onSuccess(base_data.getData());
        } else {
            if (base_data.getError() == NEED_LOGIN) {
                //重新登录
//                MyApplication.getUser().deleteUser();
//                JPushInterface.stopPush(MyApplication.getContext());
            }
            ObserverManager.getInstance().notifyObserver(OBSERVER_REQUEST_ERROR, base_data.getError());
            onFailure(base_data.getError(), base_data.getMessage());
        }
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        Logger.e("RxResultSubscriber", e.getMessage());
        String tipMsg;//错误提示
        if (e instanceof JsonSyntaxException) {
            tipMsg = "数据解析出错";
        } else if (e instanceof SocketTimeoutException) {
            tipMsg = "链接超时";
        } else if (e instanceof ConnectException) {
            if (e.getMessage().contains("Network is unreachable"))
                tipMsg = "无网络";
            else if (e.getMessage().contains("failed to connect to")) {
                tipMsg = "链接服务器失败";
            } else {
                tipMsg = "网络不给力啊";
            }
        } else {
            tipMsg = "异常";
        }
        onFailure(FAILURE, tipMsg);
    }

    protected void onFailure(int code, String tipMsg){}

    protected abstract void onSuccess(DATA dataSource);

    @Override
    public void onComplete() {

    }
}
