package com.app.http;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.app.ResponseParser;
import org.xutils.http.request.UriRequest;

import java.lang.reflect.Type;

public class Parser implements ResponseParser<String> {

    @Override
    public void beforeRequest(UriRequest request) throws Throwable {
        // custom check params?
        LogUtil.d(request.getParams().toString());
    }

    @Override
    public void afterRequest(UriRequest request) throws Throwable {
        // custom check response Headers?

    }

    @Override
    public Object parse(Type resultType, Class<?> resultClass, String result) throws Throwable {
        try {
            LogUtils.d("JSON" + result);
            JSONObject jsonObject;

            jsonObject = new JSONObject(result);

            if (jsonObject.has("data")) {
                String data = jsonObject.optString("data");
                if (ObjectUtils.isEmpty(data))
                    jsonObject.remove("data");
            }
            return JSON.parseObject(jsonObject.toString(), resultType);
        }
        catch (JSONException e) {
            LogUtils.e(e);
            return new BaseBean();
        }
    }
}
