package com.utic.center.utic.traf.server.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jetbrains.annotations.NotNull;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

@Slf4j
@ToString
@Configuration
@MapperScan(
        basePackages="com.utic.center.utic.traf.server.dao.mapper.utic",
        sqlSessionFactoryRef = "sqlSessionFactory")
@EnableTransactionManagement
public class DatabaseUticConfig {

    @Value("${spring.datasource.hikari.utic.mapper-locations:classpath:mybatis/mapper/utic/**/*.xml}")
    String mapperLocations;

    @Value("${spring.datasource.hikari.utic.jdbc-url}")
    String jdbcUrl;

    @PostConstruct
    private void init() {
        if (this.mapperLocations.trim().isEmpty()) {
            this.mapperLocations = "classpath:mybatis/mapper/utic/**/*.xml";
        }
        log.info("mapperLocations-utic: {}", this.mapperLocations);
    }

    @Primary
    @Bean(name="dataSource")
    @ConfigurationProperties(prefix="spring.datasource.hikari.utic")
    public DataSource dataSource() {
        HikariDataSource dataSource = DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .build();

        // 커넥션 초기화 SQL 설정 (Oracle 세션에 MODULE, ACTION 기록)
        if (this.jdbcUrl != null && this.jdbcUrl.toLowerCase().contains("oracle")) {
            String initSql = getString();
            dataSource.setConnectionInitSql(initSql);
        }
        return dataSource;
//        return DataSourceBuilder.create().build();
//        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    private static @NotNull String getString() {
        final String moduleName = "utic-traf-server";
        final String actionName = "ITS Traffic Processing";
//            final String clientIdentifier = "its";
//            final String clientInfo = "BatchJob: TrafficProcessor v1.2";
//            return new OracleAwareDataSource(hikari, this.moduleName, actionName, clientIdentifier, clientInfo);
        final String connInitSql;
        connInitSql = String.format(
                "BEGIN DBMS_APPLICATION_INFO.SET_MODULE('%s', '%s'); END;",
                moduleName, actionName
        );
        return connInitSql;
    }

    @Primary
    @Bean({"sqlSessionFactory", "prio", "prioetc", "moct"})
    public SqlSessionFactory sqlSessionFactoryBean(@Autowired @Qualifier("dataSource") DataSource dataSource, ApplicationContext applicationContext)
            throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(applicationContext.getResources(this.mapperLocations));
        return factoryBean.getObject();
    }

    @Primary
    @Bean(name="sqlSession")
    public SqlSessionTemplate sqlSession(@Autowired @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Primary
    @Bean(name="sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(
            @Autowired @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Primary
    @Bean(name="transactionManager")
    public DataSourceTransactionManager transactionManager(@Autowired @Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
