package net.northking.cctp.common.db.mode;

import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 读写分离模式动态数据源
 *
 * @author xiusong.xie
 * @since 2.4
 */
public class SingleClusterDataSource extends AbstractClusterDataSource
{

  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(SingleClusterDataSource.class);

  private ClassLoader classLoader;

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

  /**
   * 数据源集群
   */
  private static final DataSourceCluster DATA_SOURCE_CLUSTER = new DataSourceCluster();

  /**
   * 数据源集群配置
   */
  private List<DataSourceConfig> clusterProperties = new ArrayList<>();

  public void setClusterProperties(List<DataSourceConfig> clusterProperties)
  {
    this.clusterProperties = clusterProperties;
  }

  @Override
  public void afterPropertiesSet()
  {
    if (clusterProperties == null || clusterProperties.isEmpty())
    {
      throw new IllegalArgumentException("未配置数据源集群'nk.data-source.cluster'");
    }
    for (DataSourceConfig config : clusterProperties)
    {
      HikariDataSource dataSource = createDataSource(config);
      if (config.isReadOnly())
      {
        DATA_SOURCE_CLUSTER.putReadDataSource(config.getName(), dataSource);
      } else
      {
        DATA_SOURCE_CLUSTER.putWriteDataSource(config.getName(), dataSource);
      }
    }
  }

  @Override
  public Connection getConnection() throws SQLException
  {
    Connection connection;
    if (DataBaseModeContext.isReadMode())
    {
      connection = DATA_SOURCE_CLUSTER.getReadConnection();
    } else
    {
      connection = DATA_SOURCE_CLUSTER.getWriteConnection();
    }

    DataBaseModeContext.unload();
    return connection;
  }

  @Override
  public Connection getConnection(String username, String password) throws SQLException
  {
    Connection connection;
    if (DataBaseModeContext.isReadMode())
    {
      connection = DATA_SOURCE_CLUSTER.getReadConnection(username, password);
    } else
    {
      connection = DATA_SOURCE_CLUSTER.getWriteConnection(username, password);
    }
    DataBaseModeContext.unload();
    return connection;
  }


}
