package su.xserver.iikocon.service;

import io.vertx.core.Vertx;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.PoolOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import su.xserver.iikocon.config.DatabaseConfig;

public class DataBaseService {
  private final Logger log = LoggerFactory.getLogger("[DataBaseService]");
  private final DatabaseConfig config;
  private final Pool pool;

  public DataBaseService(Vertx vertx, DatabaseConfig config) {
    log.info("Initialization");
    this.config = config;
    this.pool = Pool.pool(vertx, this.getMySQLConnectOptions(), this.getPoolOptions());
  }

  public Pool getPool() {
    return this.pool;
  }

  public void disconnect() {
    this.pool.close();
    log.info("Connection is closed!");
  }

  private MySQLConnectOptions getMySQLConnectOptions() {
    return new MySQLConnectOptions()
      .setHost(this.config.host)
      .setPort(this.config.port)
      .setDatabase(this.config.database)
      .setUser(this.config.user)
      .setPassword(this.config.password);
  }

  private PoolOptions getPoolOptions() {
    return new PoolOptions()
      .setMaxSize(this.config.maxPoolSize)
      .setConnectionTimeout(this.config.connectionTimeout)
      .setName(this.config.database);
  }
}
