package cn.dankal.basiclib.exception;


import android.util.SparseArray;

import androidx.annotation.NonNull;

import cn.dankal.basiclib.util.Logger;

public class ApiException extends RuntimeException {

    private static final SparseArray<String> CODES = new SparseArray<>();

    static {
        // TODO: 2017/8/12-16:36 接口约定的异常
//        CODES.put(401, "请先登录");
//        CODES.put(402, "请求参数问题");
//        CODES.put(500, "数据异常或服务器异常问题");
//        CODES.put(501, "部分商品或商品规格已下架");
//        CODES.put(502, "部分结算商品库存不足");
//        CODES.put(502, "部分结算商品库存不足");
    }

    /**
     * 接口返回的响应码
     * 特殊值:
     * -2为网络响应的code解析失败
     * -1为默认未设置
     */
    int responseCode;
    String responseMessage;
    Object extra;

    public ApiException(int code, @NonNull String message) {
        super(message);
        responseCode = code;
        responseMessage = message;
        formatMsg();
    }

    public ApiException(@NonNull String code, @NonNull String message) {
        super(message);
        try {
            responseCode = Integer.parseInt(code);
            responseMessage = message;
        } catch (Exception e) {
            Logger.e("responseCode parse failed. code  : " + code);
            responseCode = -2;
        }
        formatMsg();
    }

    private void formatMsg() {
        for (int i = 0; i < CODES.size(); i++) {
            int key = CODES.keyAt(i);
            if (key == responseCode ) {
                /*if (key == responseCode && (responseMessage == null || responseMessage.isEmpty())) {*/
                responseMessage = CODES.valueAt(i);
                return;
            }
        }
    }

    public ApiException setExtra(Object extra) {
        this.extra = extra;
        return this;
    }

    @Override
    public String toString() {
        return "ApiException{" +
                "super = " + super.toString() +
                ", responseCode=" + responseCode +
                ", responseMessage='" + responseMessage + '\'' +
                '}';
    }

}

