package com.oo.seex.netlibrary.net.response;

import com.app.baselibrary.commonUtil.ToastUtil;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;

import rx.Subscriber;

/**
 * rxjava 封装的Subscriber
 */

public abstract class RxCallback<T extends IResponse> extends Subscriber<T> {

    @Override
    public void onCompleted() {
    }

    @Override
    public void onError(Throwable t) {
        t.printStackTrace();
        String errorMessage = "获取数据失败";
        if (t instanceof SocketTimeoutException) {
            errorMessage = "服务器响应超时";
            ToastUtil.showMessage(errorMessage);
        } else if (t instanceof ConnectException) {
            errorMessage = "网络连接异常，请检查网络";
            ToastUtil.showMessage(errorMessage);
        } else if (t instanceof RuntimeException) {
            errorMessage = "运行时错误";
        } else if (t instanceof UnknownHostException) {
            errorMessage = "无法解析主机，请检查网络连接";
            ToastUtil.showMessage(errorMessage);
        } else if (t instanceof UnknownServiceException) {
            errorMessage = "未知的服务器错误";
        }
        onError(-1, errorMessage);
    }

    @Override
    public void onNext(T response) {
        try {
            if (response.isSuccess()) {
                onSuccess(response);
            } else {
                onError(response.getResultCode(), response.getResultMssage());
            }
        }catch (Exception e){
            e.printStackTrace();
            onError(-1, "Json 数据解析异常");
        }
    }
    protected abstract void onSuccess(T t);

    protected abstract void onError(int errorCode, String errorMessage);
}
