package su.xserver.iikocon.service;

import io.vertx.core.Vertx;
import io.vertx.redis.client.Redis;
import io.vertx.redis.client.RedisAPI;
import io.vertx.redis.client.RedisOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import su.xserver.iikocon.config.RedisConfig;

public class RedisService {
  private final Logger log = LoggerFactory.getLogger("[RedisService]");
  private final RedisConfig config;
  private final Redis redis;

  public RedisService(Vertx vertx, RedisConfig config) {
    log.info("Initialization");
    this.config = config;
    this.redis = Redis.createClient(vertx, this.getRedisOptions());
  }

  public Redis getRedis() {
    return this.redis;
  }

  public RedisAPI getRedisApi() {
    return RedisAPI.api(this.redis);
  }

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

  private RedisOptions getRedisOptions() {
    RedisOptions options = new RedisOptions()
      .addConnectionString(String.format("redis://%s:%s",
        this.config.host,
        this.config.port))
      .setMaxPoolSize(this.config.maxPoolSize)
      .setMaxWaitingHandlers(this.config.maxWaitingHandlers);

    if (this.config.password != null) {
      options.setPassword(this.config.password);
    }
    return options;
  }
}
