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

import android.util.Log;

import com.app.baselibrary.commonUtil.TextUtils;
import com.google.gson.Gson;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 非rxjava  封装网络返回值
 */

public abstract class ACallBack<T extends IResponse> implements Callback<T> {

    private static Gson sGson = new Gson();

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        try {
            if (response.isSuccessful()) {
                if (response.body().isSuccess()) {
                    onSuccess(call, response.body());
                } else {
                    onError(response.body().getResultCode(), response.body().getResultMssage());
                }
            } else {
                String errorBodyStr = "";
                try {
                    errorBodyStr = TextUtils.convertUnicode(response.errorBody().string());
                } catch (IOException ioe) {
                    Log.e("errorBodyStr ioe:", ioe.toString());
                }

                try {
                    IResponse errorResponse = sGson.fromJson(errorBodyStr, IResponse.class);
                    if (null != errorResponse) {
                        onError(errorResponse.getResultCode(), errorResponse.getResultMssage());
                    } else {
                        onError(-1, "ErrorResponse is null ");
                    }
                } catch (Exception exception) {
                    onError(-1, "Json 数据解析异常");
                    exception.printStackTrace();
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            onError(-1, "Json 数据解析异常");
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        t.printStackTrace();

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

    public abstract void onSuccess(Call<T> call, T t);

    public abstract void onError(int errorCode, String errorMessage);

}
