package com.bcxin.backend.domain.configs;
import com.bcxin.backend.domain.models.DomainSuperviseDTO;
import com.bcxin.backend.domain.models.SuperviseDTO;
import com.bcxin.runtime.domain.syncs.entities.DataSyncQueueEntity;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(
        basePackages = "com.bcxin.backend.domain.repositories",
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager")
@EntityScan(basePackages = "com.bcxin.backend.domain.models")
public class DomainConfig {
    public DomainConfig() {

    }

    @Primary
    @Bean("dataSourceProperties")
    @ConfigurationProperties("spring.datasource")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Primary
    @Bean("dataSource")
    public DataSource dataSource() {
        return dataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name="jdbcTemplate")
    public JdbcTemplate jdbcTemplate (
            @Qualifier("dataSource")  DataSource dataSource ) {
        return new JdbcTemplate(dataSource);
    }

    @Primary
    @Bean("entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
            EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSource())
                .packages(DomainSuperviseDTO.class,
                        //目前将DataSyncQueue的实体也放置到该entityManagerFactory对象上
                        DataSyncQueueEntity.class)
                .build();
    }

    @Bean("transactionManager")
    public PlatformTransactionManager transactionManager(
            final @Qualifier("entityManagerFactory")
                    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
        return new JpaTransactionManager(entityManagerFactoryBean.getObject());
    }
}
