package com.jay.monitor.data.server.config.mvc;

import com.jay.monitor.data.server.config.BeanConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import java.util.EnumSet;

/**
 * Spring启动入口
 * <p>
 * 这里可以监控MVC的一些操作
 */
public class WebInitializer implements WebApplicationInitializer {
    private Logger logger = LoggerFactory.getLogger(WebInitializer.class);

    @Override
    public void onStartup(ServletContext servletContext) {
        logger.info("begin init web application.");
        long startTime = System.currentTimeMillis();
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        //配置Spring
        AnnotationConfigWebApplicationContext springContext = new AnnotationConfigWebApplicationContext();
        springContext.register(BeanConfig.class);

        //添加linstener
        servletContext.addListener(new ContextLoaderListener(springContext));

        //添加servlet
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                "dispatcher", new DispatcherServlet(springContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

//        CorsFilter corsFilter = new CorsFilter();
//        FilterRegistration.Dynamic corsFilterRegistration = servletContext.addFilter("corsFilter", corsFilter);
//        corsFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), false, "/*");

        FilterRegistration.Dynamic filter = servletContext.addFilter("encoding", characterEncodingFilter);
        filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), false, "/*");

        long time = System.currentTimeMillis() - startTime;
        logger.info("init web application success. start count time : " + time);
    }

}