package com.lion.lionwebsite.Configuration;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class SqlConfiguration {
    @Bean(name = "datasource-main")
    @ConfigurationProperties(prefix = "spring.datasource-main")
    public DataSource dataSourceMain() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "datasource-cache")
    @ConfigurationProperties(prefix = "spring.datasource-cache")
    public DataSource dataSourceCache() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sqlSessionFactory-main")
    public SqlSessionFactory sqlSessionFactoryMain(@Qualifier("datasource-main") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "sqlSessionFactory-cache")
    public SqlSessionFactory sqlSessionFactoryCache(@Qualifier("datasource-cache") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "sqlSessionTemplate-main")
    public SqlSessionTemplate sqlSessionTemplateMain(@Qualifier("sqlSessionFactory-main") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "sqlSessionTemplate-cache")
    public SqlSessionTemplate sqlSessionTemplateCache(@Qualifier("sqlSessionFactory-cache") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
