package eu.dnetlib.is;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
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.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 org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "mainEntityManagerFactory", transactionManagerRef = "mainTransactionManager", basePackages = {
	"eu.dnetlib.data.is"
})
public class MainDBConfig {

	@Primary
	@Bean(name = "mainDataSource")
	@ConfigurationProperties(prefix = "is.datasource")
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}

	@Primary
	@Bean(name = "mainEntityManagerFactory")
	public LocalContainerEntityManagerFactoryBean entityManagerFactory(
		final EntityManagerFactoryBuilder builder,
		@Qualifier("mainDataSource") final DataSource ds) {
		return builder
			.dataSource(ds)
			.packages("eu.dnetlib.data.is")
			.persistenceUnit("is")
			.build();
	}

	@Primary
	@Bean(name = "mainTransactionManager")
	public PlatformTransactionManager transactionManager(
		@Qualifier("mainEntityManagerFactory") final EntityManagerFactory emf) {
		return new JpaTransactionManager(emf);
	}

	@Primary
	@Bean(name = "mainJdbcTemplate")
	public JdbcTemplate jdbcTemplate1(@Qualifier("mainDataSource") final DataSource ds) {
		return new JdbcTemplate(ds);
	}

}
