package com.sy.coinage.core.respconverter;

import com.sy.coinage.core.annotation.FastJsonFieldProfile;
import com.sy.coinage.core.resp.ReturnJson;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Objects;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * - 全局处理controller返回null转换为空字符串
 *
 * @author: lug 2022年6月7日
 */
@RestControllerAdvice
public class ResponseBodyAnalysis implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                    Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                    ServerHttpResponse response) {
        if (null == body) {
            new ReturnJson("");
        }
        String requestPath = request.getURI().getPath();
        if (requestPath.contains("/v2/api-docs") || requestPath.contains("/swagger-resources")) {
            return body;
        }
        if (body instanceof ReturnJson) {
            return body;
        }
        return new ReturnJson(body);
    }

    private HashSet<String> getFieldsShouldInclude(String activeFastJsonProfile, Class<?> clazz) {
        HashSet<String> includedFieldSet = new HashSet<>();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            /**
             * 获取field上的FastJsonFieldProfile注解，然后检查注解上的profile，看看该profile是否 匹配看看该field是否需要被加入
             */
            FastJsonFieldProfile[] annotationsByType = declaredField.getAnnotationsByType(FastJsonFieldProfile.class);
            if (annotationsByType == null || annotationsByType.length == 0) {
                continue;
            }
            fieldLoop: for (FastJsonFieldProfile fastJsonFieldProfile : annotationsByType) {
                for (String profile : fastJsonFieldProfile.groups()) {
                    if (Objects.equals(profile, activeFastJsonProfile)) {
                        includedFieldSet.add(declaredField.getName());
                        continue fieldLoop;
                    }
                }
            }
        }
        return includedFieldSet;
    }

}
