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

import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
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.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

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

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

    private final ApplicationConfig config;

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

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

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

    @Bean(name="moctDataSource")
    @ConfigurationProperties(prefix="spring.datasource.hikari.moct")
    public DataSource moctDataSource() {
        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 @NotNull String getString() {
        final String moduleName = this.config.getProcessName();
        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;
    }

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

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

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

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