package com.chenyang.nse.bussiness.config;

import java.io.IOException;
import java.security.Security;
import java.util.Objects;
import java.util.Properties;
import javax.sql.DataSource;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

@Configuration
public class HibernateConfig {
   @Autowired
   private Environment environment;
   @Autowired
   private DataSource dataSource;
   private static Properties properties = null;
   public static String PEIZHIKUDBTYPE = null;

   @Bean
   public LocalSessionFactoryBean sessionFactoryBean() {
      LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
      sessionFactoryBean.setDataSource(this.dataSource);
      sessionFactoryBean.setPackagesToScan(new String[]{"com.chenyang.nse.bussiness"});
      sessionFactoryBean.setHibernateProperties(this.hibernateProperties());
      return sessionFactoryBean;
   }

   private Properties hibernateProperties() {
      Properties properties = new Properties();
      properties.setProperty("hibernate.current_session_context_class", this.environment.getProperty("spring.jpa.properties.hibernate.current_session_context_class"));
      properties.setProperty("hibernate.hbm2ddl.auto", this.environment.getProperty("spring.jpa.hibernate.ddl-auto"));
      properties.setProperty("hibernate.show_sql", this.environment.getProperty("spring.jpa.properties.hibernate.show_sql"));
      properties.setProperty("hibernate.format_sql", this.environment.getProperty("spring.jpa.properties.hibernate.format_sql"));
      properties.setProperty("hibernate.cache.use_second_level_cache", this.environment.getProperty("spring.jpa.properties.hibernate.cache.use_second_level_cache"));
      properties.setProperty("hibernate.cache.use_query_cache", this.environment.getProperty("spring.jpa.properties.hibernate.cache.use_query_cache"));
      if (Objects.equals(PEIZHIKUDBTYPE, "1")) {
         properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Kingbase8Dialect");
      } else if (Objects.equals(PEIZHIKUDBTYPE, "2")) {
         properties.setProperty("hibernate.dialect", "org.hibernate.dialect.DmDialect");
      } else if (Objects.equals(PEIZHIKUDBTYPE, "3")) {
         properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
      }

      return properties;
   }

   static {
      try {
         properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
         PEIZHIKUDBTYPE = properties.get("peizhikudbtype").toString();
      } catch (IOException e) {
         e.printStackTrace();
      }

      Security.addProvider(new BouncyCastleProvider());
   }
}
