package com.usoftchina.uas.office.jdbc;

import com.usoftchina.uas.office.util.StringUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;

import java.sql.SQLException;

/**
 * 数据源动态注册
 *
 * @author yingp
 * @date 2017/7/27
 */
public class DynamicDataSourceRegister {

    private DataSourceProperties defaultProperties;
    private DynamicDataSource dynamicDataSource;
    private Logger logger = LoggerFactory.getLogger(getClass());

    public DynamicDataSourceRegister(DataSourceProperties defaultProperties, DynamicDataSource dynamicDataSource) {
        this.defaultProperties = defaultProperties;
        this.dynamicDataSource = dynamicDataSource;
    }

    public void register(DataSourceBean bean) throws SQLException {
        if (!dynamicDataSource.containsDataSource(bean)) {
            logger.info(bean.info());
            HikariDataSource dataSource = DataSourceBuilder.create(defaultProperties.getClassLoader())
                    .type(HikariDataSource.class)
                    .driverClassName(StringUtils.nvl(bean.driverClassName(), defaultProperties.determineDriverClassName()))
                    .url(StringUtils.nvl(bean.url(), dynamicDataSource.getJdbcUrl()))
                    .username(bean.username())
                    .password(bean.password())
                    .build();
            dynamicDataSource.addDataSource(bean, dataSource);
        }
    }

    public void unregister(DataSourceBean bean) {
        dynamicDataSource.removeDataSource(bean);
    }
}
