package com.malk.aipocloud;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import javax.persistence.EntityManager;

/**
 * corp项目: 扫描公共模块
 * -
 * 若是无需数据库模块, 配置无效地址也可启动, 引入mjava不支持直接 @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) 配置
 * 需要配置 jpa.hibernate.ddl-auto 为 none. 标识对表没有任何操作. 若不设置为 none, flyway.enabled 配置会无效, 在没有数库连接情况下程序无法启动
 */
@EnableJpaAuditing
@SpringBootApplication(scanBasePackages = {"com.malk"})
public class Boot {

    public static void main(String... args) {
        SpringApplication.run(Boot.class, args);
    }

    /**
     * 让Spring管理JPAQueryFactory [不使用Qualifier详见mjava-Boot]
     */
    @Bean
    public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) {
        return new JPAQueryFactory(entityManager);
    }

    /**
     * todo 是否集成到基础框架
     * 配置Tomcat下Https [访问格式为: https + 域名 + 端口 + 路径]
     * 1. 在resource下添加/ssl/证书, jsk后缀文件 (证书类型为jks, 非Tomcat下pfx)
     * 2. yml文件配置ssl: 路径\密码\类型(JKS)  [密码\路径不对程序启动异常]
     * 3. 启动类重定向和端口 (http服务于默认端口服务不能是同一个端口, 相当于是同时启动两个端口)
     */
    @Bean
    public ServletWebServerFactory servletContainer() {

        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(createHTTPConnector());
        return tomcat;
    }

    @Value("${server.ssl.http}")
    private int httpPort;

    private Connector createHTTPConnector() {

        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        // ppExt: 同时启用http服务端口, 原默认端口只能https访问, 此处http端口仅支持http访问 [证书匹配后, localhost/127.0.0.1仅支持https访问]
        connector.setScheme("http");
        connector.setSecure(false);
        connector.setPort(httpPort);
        connector.setRedirectPort(httpPort);
        return connector;
    }
}