/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.common.db.mode;

import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.util.StringUtils;

/**
 * 集群数据源抽象类
 *
 * @author : xiusong.xie
 * @version : 1.0
 */
public abstract class AbstractClusterDataSource extends AbstractDataSource implements BeanClassLoaderAware, InitializingBean
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(AbstractClusterDataSource.class);

  private ClassLoader classLoader;

  @Override
  public void setBeanClassLoader(ClassLoader classLoader)
  {
    this.classLoader = classLoader;
  }

  protected HikariDataSource createDataSource(DataSourceConfig config)
  {
    HikariDataSource dataSource = DataSourceBuilder.create(this.classLoader).type(HikariDataSource.class).driverClassName(config.getDriverClassName())
        .url(config.getUrl()).username(config.getUsername()).password(config.getPassword()).build();
    if (StringUtils.hasText(config.getPoolName()))
    {
      dataSource.setPoolName(config.getPoolName());
    }
    dataSource.setMinimumIdle(config.getMinIdle());
    dataSource.setMaximumPoolSize(config.getMaxPoolSize());
    dataSource.setAutoCommit(config.isAutoCommit());
    dataSource.setReadOnly(config.isReadOnly());
    if (logger.isDebugEnabled())
    {
      logger.debug("创建数据源HikariDataSource：poolName={}, maxPoolName={}, minIdle={}, readOnly={}",
          config.getPoolName(), config.getMaxPoolSize(), config.getMinIdle(), config.isReadOnly());
    }
    return dataSource;
  }
}
