package com.github.microservice.core.mvc;

import com.github.microservice.core.util.result.InvokerExceptionResolver;
import com.github.microservice.core.util.result.InvokerResult;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.util.StringUtils;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Vector;
import java.util.regex.Pattern;

@Slf4j
@Configuration
public class MVCResponseConfiguration {


    /**
     * 通用的异常捕获
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public InvokerExceptionResolver invokerExceptionResolver() {
        return new InvokerExceptionResolver();
    }


    @Getter
    private Vector<String> ignoreUrls = new Vector() {{
        add(("^/actuator/.*"));// /v3/api-docs
        add(("^/v3/.*"));// /v3/api-docs
        add((".*manager.*")); // **manager**
        add(("/error")); // /error
    }};


//    @Bean
//    @ConditionalOnMissingBean
//    public ResponseBodyAdvice responseBodyAdvice() {
//        return new UserApiResponseBodyAdvice();
//    }


    //    @RestControllerAdvice
    public class UserApiResponseBodyAdvice 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) {

            //url判断过滤
            final String path = request.getURI().getPath();

            if (StringUtils.hasText(path)) {
                for (String expression : ignoreUrls) {
                    if (Pattern.compile(expression).matcher(path).find()) {
                        return body;
                    }
                }
            }

            return InvokerResult.notNull(body);
        }


    }


}
