package network.config.applyOptions;

import android.content.Context;
import android.net.ParseException;

import com.gingersoft.gsa.cloud.network.R;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.jess.arms.utils.ArmsUtils;
import com.joe.base.utils.log.LogUtil;
import com.joe.base.utils.toast.ToastUtils;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import me.jessyan.rxerrorhandler.handler.listener.ResponseErrorListener;
import retrofit2.HttpException;
import timber.log.Timber;


public class MyResponseErrorListener implements ResponseErrorListener {
    @Override
    public void handleResponseError(Context context, Throwable t) {
        /* 用来提供处理所有错误的监听
           rxjava必要要使用ErrorHandleSubscriber(默认实现Subscriber的onError方法),此监听才生效 */
        Timber.tag("Catch-Error").w(t.getMessage());
        //这里不光是只能打印错误,还可以根据不同的错误作出不同的逻辑处理
        String msg = ArmsUtils.getString(context, R.string.response_error_unknown_error);
        if (t instanceof UnknownHostException) {
            msg = ArmsUtils.getString(context, R.string.response_error_network_unavailable);
        } else if (t instanceof SocketTimeoutException) {
            msg = ArmsUtils.getString(context, R.string.response_error_request_timeout);
        } else if (t instanceof HttpException) {
            HttpException httpException = (HttpException) t;
            msg = convertStatusCode(context, httpException);
        } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) {
            msg = ArmsUtils.getString(context, R.string.response_error_data_parsing_error);
        }
//        ArmsUtils.snackbarText(msg);
        LogUtil.d("handleResponseError: " + t.getMessage());
        ToastUtils.show(context, msg);
    }

    private String convertStatusCode(Context context, HttpException httpException) {
        String msg;
        if (httpException.code() == 500) {
            msg = ArmsUtils.getString(context, R.string.response_error_server_error);
        } else if (httpException.code() == 404) {
            msg = ArmsUtils.getString(context, R.string.response_error_address_does_not_exist);
        } else if (httpException.code() == 403) {
            msg = ArmsUtils.getString(context, R.string.response_error_request_rejected_by_server);
        } else if (httpException.code() == 307) {
            msg = ArmsUtils.getString(context, R.string.response_error_request_was_redirected_to_another_page);
        } else {
            msg = httpException.message();
        }
        return msg;
    }
}
