package com.xxx.base.springframework.core.web.handler;

import com.google.common.collect.Sets;
import com.xxx.base.springframework.constant.vo.ResponseData;
import com.xxx.base.springframework.util.RegexUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Bean;
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.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Set;

@Slf4j
@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice<Object> {

    // 只对以下路径进行封装 以防封装到spring以及第三方接口导致出现问题情况
    private static final String PACKAGE_PATH = ".*.modulesV2.controller.*";

    private static final Set<String> FILTER_URI = Sets.newHashSet("/onLinePayment/notify");

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {

        // 如果不是controller包下的不进行封装 以防封装到spring以及第三方接口导致出现问题情况
        if (!RegexUtil.matcher(PACKAGE_PATH, methodParameter.getExecutable().getDeclaringClass().getName())) {
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    @Override
    public Object beforeBodyWrite(Object t, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> httpMessageConverter,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (CollectionUtils.containsAny(FILTER_URI, serverHttpRequest.getURI().getPath())) {
            return t;
        }

        return ResponseData.success(t);
    }
}