package cn.reghao.oss.store.config.web;

import cn.reghao.oss.store.inerceptor.AccessLogInterceptor;
import cn.reghao.oss.store.inerceptor.TokenFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.Filter;
import java.util.List;

/**
 * @author reghao
 * @date 2021-12-30 12:34:26
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    private final AccessLogInterceptor accessLogInterceptor;

    public WebConfig(AccessLogInterceptor accessLogInterceptor) {
        this.accessLogInterceptor = accessLogInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(accessLogInterceptor);
    }

    // 跨域处理
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    @Bean
    public FilterRegistrationBean<Filter> filterRegistrationBean(TokenFilter tokenFilter) {
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(tokenFilter);
        registrationBean.addUrlPatterns("*");
        return registrationBean;
    }

    /**
     * HTTP req/resp 消息转换器
     *
     * @param
     * @return
     * @date 2022-12-29 上午9:43
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 处理 application/octet-stream 数据
        converters.add(new PutMessageConverter());
        // 处理 application/json 数据
        converters.add(new StringHttpMessageConverter());
        converters.add(new MappingJackson2HttpMessageConverter());
        // 处理 application/xml 数据
        converters.add(new Jaxb2RootElementHttpMessageConverter());
    }
}
