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.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 = "openaireEntityManagerFactory", transactionManagerRef = "openaireTransactionManager", basePackages = {
	"eu.dnetlib.data.openaire"
})
public class OpenaireDBConfig {

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

	@Bean(name = "openaireEntityManagerFactory")
	public LocalContainerEntityManagerFactoryBean openaireEntityManagerFactory(
		final EntityManagerFactoryBuilder builder,
		@Qualifier("openaireDataSource") final DataSource ds) {
		return builder
			.dataSource(ds)
			.packages("eu.dnetlib.data.openaire")
			.persistenceUnit("openaire")
			.build();
	}

	@Bean(name = "openaireTransactionManager")
	public PlatformTransactionManager opeanaireTransactionManager(
		@Qualifier("openaireEntityManagerFactory") final EntityManagerFactory emf) {
		return new JpaTransactionManager(emf);
	}

	@Bean(name = "openaireJdbcTemplate")
	public JdbcTemplate jdbcTemplate1(@Qualifier("openaireDataSource") final DataSource ds) {
		return new JdbcTemplate(ds);
	}
}
