package ru.yandex.webmaster3.storage.util.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import java.util.concurrent.TimeUnit;

/**
 * @author aherman
 */
public class CuratorZookeeperFactory {
    private static final Logger log = LoggerFactory.getLogger(CuratorZookeeperFactory.class);

    private String zookeeperConnectionString;
    private ZookeeperTracerService zookeeperTracerService;

    private int sessionTimeoutMs = (int) TimeUnit.MINUTES.toMillis(1);
    private int connectionTimeoutMs = (int) TimeUnit.SECONDS.toMillis(5);

    public CuratorFramework createClient() {
        log.info("Create ZooKeeper curator client: {}", zookeeperConnectionString);
        CuratorFramework framework = CuratorFrameworkFactory.builder()
                .connectString(zookeeperConnectionString)
                .sessionTimeoutMs(sessionTimeoutMs)
                .connectionTimeoutMs(connectionTimeoutMs)
                .retryPolicy(new RetryNTimes(120, 1_000))
                .build();
        framework.getZookeeperClient().setTracerDriver(zookeeperTracerService.getTraceDriver());
        return framework;
    }

    @Required
    public void setZookeeperConnectionString(String zookeeperConnectionString) {
        this.zookeeperConnectionString = zookeeperConnectionString;
    }

    @Required
    public void setZookeeperTracerService(ZookeeperTracerService zookeeperTracerService) {
        this.zookeeperTracerService = zookeeperTracerService;
    }

    public void setSessionTimeoutMs(int sessionTimeoutMs) {
        this.sessionTimeoutMs = sessionTimeoutMs;
    }

    public void setConnectionTimeoutMs(int connectionTimeoutMs) {
        this.connectionTimeoutMs = connectionTimeoutMs;
    }
}
