package xyz.wbsite.dbtool.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xyz.wbsite.dbtool.web.frame.utils.LogUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${web.welcome.page}")
    private String homePage;
    @Value("${spring.mvc.static-path-pattern}")
    private String[] staticPath;

    /**
     * 增加全局拦截器，可用于异常日志的收集
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 全局异常收集拦截器
        registry.addInterceptor(new HandlerInterceptorAdapter() {

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                super.afterCompletion(request, response, handler, ex);

                if (ex != null) {
                    LogUtil.dumpException(ex);
                }
            }

        }).addPathPatterns("/**").excludePathPatterns(staticPath);
    }

    /**
     * Jackson序列化时的转化规则配置
     * <p>
     * 1、Long或long类型在序列化时转String，防止出现javascript中Number精度丢失的情况。
     *
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
                SimpleModule simpleModule = new SimpleModule();
                simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
                simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
                objectMapper.registerModule(simpleModule);
            }
        }
    }

//    @Bean
//    @Profile("prod")
//    public ServletWebServerFactory servletContainer() {
//        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
//
//        // 基本参数
//        String keyStore = "1754557_www.wbsite.xyz.pfx";
//        String keyStorePassword = "s98n7CLd";
//        String keyStoreType = "PKCS12";
//        int httpsPort = 443;
//
//        File keystore = null;
//        // 正常开发可以通过getFile()获取，打包jar后无法直接获取File对象，需将文件考出
//        try {
//            keystore = new ClassPathResource(keyStore).getFile();
//        } catch (IOException ex) {
//            try {
//                ApplicationHome home = new ApplicationHome(getClass());
//                // 当前运行jar文件
//                File jarFile = home.getSource();
//                //jar同目录
//                keystore = new File(jarFile.getParent(), keyStore);
//
//                InputStream inputStream = new ClassPathResource(keyStore).getInputStream();
//                byte[] bytes = new byte[inputStream.available()];
//
//                inputStream.read(bytes);
//
//                inputStream.close();
//
//                FileOutputStream fileOutputStream = new FileOutputStream(keystore);
//                fileOutputStream.write(bytes);
//                fileOutputStream.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//        // 创建Connector
//        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
//        connector.setScheme("https");
//        connector.setSecure(true);
//        connector.setPort(httpsPort);
//        protocol.setSSLEnabled(true);
//        protocol.setKeystoreFile(keystore.getAbsolutePath());
//        protocol.setKeystorePass(keyStorePassword);
//        protocol.setKeystoreType(keyStoreType);
//
//        // 添加
//        tomcat.addAdditionalTomcatConnectors(connector);
//        return tomcat;
//    }
}