package com.shanghaichengdi.ghjgitem.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

  private final List<String> excludePathList = new ArrayList<>(
      Arrays.asList("/auth/**", "/login/**", "/error/**"));
  @Resource
  private AuthenticationInterceptor authenticationInterceptor;
  @Resource
  private PermissionsVerifyInterceptor permissionsVerifyInterceptor;
  @Resource
  private FrequencyLimitInterceptor frequencyLimitInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**")
        .excludePathPatterns(excludePathList);
    registry.addInterceptor(permissionsVerifyInterceptor).addPathPatterns("/**")
        .excludePathPatterns(excludePathList);
    registry.addInterceptor(frequencyLimitInterceptor).addPathPatterns("/**")
        .excludePathPatterns(excludePathList);
  }

  //让cors高于拦截器的权限
  @Bean
  public CorsFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowCredentials(true);
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
    configSource.registerCorsConfiguration("/**", config);
    return new CorsFilter(configSource);
  }
}
