package at.procon.dip.domain.time.leitstand.config;

import at.procon.dip.domain.time.config.TimeDomainProperties;
import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;
import javax.sql.DataSource;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@Configuration
@ConditionalOnRuntimeMode(RuntimeMode.NEW)
@ConditionalOnProperty(prefix = "dip.time.leitstand", name = "enabled", havingValue = "true")
@RequiredArgsConstructor
public class LeitstandTimeImportConfiguration {

    private final TimeDomainProperties properties;


    private DataSource createLeitstandDataSource() {
        var jdbc = properties.getLeitstand().getJdbc();
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(jdbc.getDriverClassName());
        ds.setUrl(jdbc.getUrl());
        ds.setUsername(jdbc.getUsername());
        ds.setPassword(jdbc.getPassword());
        return ds;
    }

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

    @Primary
    @Bean(name = "applicationNamedParameterJdbcTemplate")
    public NamedParameterJdbcTemplate applicationNamedParameterJdbcTemplate(DataSource dataSource) {
        return new NamedParameterJdbcTemplate(dataSource);
    }

    @Bean(name = "leitstandTimeNamedParameterJdbcTemplate")
    public NamedParameterJdbcTemplate leitstandNamedParameterJdbcTemplate() {
        return new NamedParameterJdbcTemplate(createLeitstandDataSource());
    }
}