package com.ruoyi.framework.config;

import javax.servlet.DispatcherType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor;
import com.ruoyi.framework.web.filter.LocalProfileProxyFilter;

/**
 * General web mvc config
 *
 * @author ruoyi
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{
    /**
     * Index url
     */
    @Value("${shiro.user.indexUrl}")
    private String indexUrl;

    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;

    /**
     * Register local profile redirect filter only when ruoyi.isLocalDebug=true
     */
    @Bean
    @ConditionalOnProperty(prefix = "ruoyi", name = "isLocalDebug", havingValue = "true")
    public FilterRegistrationBean<LocalProfileProxyFilter> localProfileProxyFilterRegistration()
    {
        FilterRegistrationBean<LocalProfileProxyFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new LocalProfileProxyFilter());
        registration.addUrlPatterns("/*");
        registration.setName("localProfileProxyFilter");
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE + 20);
        return registration;
    }

    /**
     * Default home page forward
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry)
    {
        registry.addViewController("/").setViewName("forward:" + indexUrl);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        /** Local upload path */
        registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + RuoYiConfig.getProfile() + "/");

        /** swagger */
        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
    }

    /**
     * Interceptors
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
    }
}
