package com.njzscloud.common.http.interceptor;

import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.http.constant.HttpMethod;
import com.njzscloud.common.http.support.RequestInfo;
import com.njzscloud.common.http.support.ResponseInfo;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;


/**
 * 组合式拦截器, 响应拦截器默认解析 JSON 类型参数
 *
 * @see RequestInterceptor
 * @see ResponseInterceptor
 */
@Slf4j
public class CompositeInterceptor implements RequestInterceptor, ResponseInterceptor {

    @Override
    public Object[] process(HttpMethod method, String url, Object[] args) {
        return null;
    }

    @Override
    public Object process(RequestInfo requestInfo, ResponseInfo responseInfo, Type responseType) {
        log.info("响应拦截器: {}、{}、{}", Jackson.toJsonStr(requestInfo), new String(responseInfo.body()), responseType);
        Object data = null;

        if (responseInfo.success()) {
            if (responseInfo.body() != null) {
                if (responseType == String.class) {
                    data = new String(responseInfo.body());
                } else {
                    data = Jackson.toBean(responseInfo.body(), responseType);
                }
            }
        } else {
            log.error("HTTP请求失败");
        }

        return data;
    }
}
