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

import com.app.baselibrary.commonUtil.CheckUtil;
import com.app.baselibrary.commonUtil.JsonUtils;
import com.app.baselibrary.commonUtil.LogUtil;
import com.app.baselibrary.commonUtil.ToastUtil;

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

import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Subscriber;

/**
 * Date : 2018/6/12.
 * Author:  cxh
 */

public abstract class RxResponseCallback <T extends IResponse> extends Subscriber<Response<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(Response<T> response) {
        try {
            T iResponse  = response.body();
            if (response.isSuccessful()) {
                if(iResponse.isSuccess()) {
                    onSuccess(iResponse);
                }else{
                    onError(response.code(),iResponse.getResultMssage());
                }
            } else {
                ResponseBody responseBody = response.errorBody();
                if(!CheckUtil.isNull(responseBody)){
                    String body =  new String(response.errorBody().bytes(),"UTF-8");
                    LogUtil.e("--------RxResponseCallback---errorBody--"+body);
                    response = JsonUtils.str2obj(body,response.getClass());
                }
                onError(response.code(),response.message());
            }
        }catch (Exception e){
            e.printStackTrace();
            onError(-1, "Json 数据解析异常");
        }
    }
    protected abstract void onSuccess(T t);

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