package ru.yandex.webmaster.common.cassandra;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.Session;

import java.io.Closeable;
import java.util.Set;

/**
 * User: azakharov
 * Date: 30.05.14
 * Time: 17:12
 */
public class CassandraClient implements Closeable {
    private Cluster cluster;
    private volatile Session session;

    public CassandraClient(Set<String> nodes) {
        Cluster.Builder builder = Cluster.builder();
        for (String node : nodes) {
            builder.addContactPoint(node);
        }
        cluster = builder.withProtocolVersion(ProtocolVersion.V3).build();
    }

    /**
     * Creates new session object.
     *
     * Use only if you need separate connection pool, otherwise use getSession
     *
     * @return
     */
    public Session createSession() {
        return cluster.connect();
    }

    /**
     * Provides singleton session object
     *
     * @return session
     */
    public Session getSession() {
        if (session == null) {
            session = createSession();
        }
        return session;
    }

    public void close() {
        cluster.close();
    }
}
