package io.senslog.database;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.jodatime2.JodaTimePlugin;
import org.jdbi.v3.postgres.PostgresPlugin;
import org.postgresql.ds.PGSimpleDataSource;

public class DBConnection {

    private Jdbi jdbi;

    public void connect(DBConfig config) {
        PGSimpleDataSource ds = new PGSimpleDataSource();
        ds.setUrl(config.getUrl());
        ds.setPassword(config.getPassword());
        ds.setUser(config.getUsername());
        ds.setLoadBalanceHosts(true);
        HikariConfig hc = new HikariConfig();
        hc.setDataSource(ds);
        hc.setMaximumPoolSize(config.getPoolSize());

        jdbi = Jdbi.create(new HikariDataSource(hc))
                .installPlugin(new PostgresPlugin())
                .installPlugin(new JodaTimePlugin());
    }

    public boolean isConnected() {
        return jdbi != null;
    }

    public Jdbi get() throws DBException {
        if (!isConnected()) {
            throw new DBException("The connection to the database has been closed.");
        }
        return jdbi;
    }
}
