package com.github.wanggit.access.frequency.autoconfigure;

import com.github.wanggit.access.frequency.AccessFrequencyFilter;
import com.github.wanggit.access.frequency.config.AccessFrequencyBeanFactoryPostProcessor;
import com.github.wanggit.access.frequency.utils.PropertiesUtils;
import com.github.wanggit.access.frequency.utils.RedisUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.ServerHttpRequest;

import javax.servlet.Filter;

@Configuration
@ConditionalOnClass({Filter.class, ServerHttpRequest.class})
@EnableConfigurationProperties(AccessFrequencyProperties.class)
@ConditionalOnProperty(prefix = "access.frequency", value = "enable", havingValue = "true")
public class AccessFrequencyAutoConfig {

    @Bean
    public AccessFrequencyBeanFactoryPostProcessor accessFrequencyBeanFactoryPostProcessor(){
        return new AccessFrequencyBeanFactoryPostProcessor();
    }

    @Bean
    public FilterRegistrationBean accessFrequencyFilterRegistrationBean(Filter accessFrequencyFilter){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(accessFrequencyFilter);
        filterRegistrationBean.setName(AccessFrequencyFilter.class.getName());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return filterRegistrationBean;
    }

    @Bean
    public Filter accessFrequencyFilter(){
        return new AccessFrequencyFilter();
    }

    @Bean
    public PropertiesUtils propertiesUtils(){
        return new PropertiesUtils();
    }

    @Bean
    public RedisUtils redisUtils(){
        return new RedisUtils();
    }

}
