package com.bcxin.backend.domain.approval.configs;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
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.approval.repositories.source",
        entityManagerFactoryRef = "bjApprovalSourceEntityManagerFactory",
        transactionManagerRef = "bjApprovalSourceTransactionManager")
@ConditionalOnProperty(prefix = "myapps.bj-approval-data-push",name = "enable",havingValue = "true")
public class BjApprovalDataPushSourceConfig {

//    @Bean("bjApprovalDataSourceProperties")
//    @ConfigurationProperties("spring.datasource.bj-approval-source")
//    public DataSourceProperties bjApprovalDataSourceProperties() {
//        return new DataSourceProperties();
//    }
    @Bean(name = "bjApprovalSourceDataSource")
    @ConfigurationProperties("spring.datasource.bj-approval-source")
    public DataSource bjApprovalSourceDataSource() {
        return DataSourceBuilder.create().build();
    }



    @Bean("bjApprovalSourceEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean bjApprovalSourceEntityManagerFactory(
            EntityManagerFactoryBuilder builder,@Qualifier("bjApprovalSourceDataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.bcxin.backend.domain.approval.entities.source")
                .build();
    }

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