package lc.sips.jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import lc.sips.Transaction;
import lc.sips.TransactionFactory;
import lc.sips.postgres.PostgresDialect;

import java.sql.SQLException;

/**
 * This implementation of {@link TransactionFactory} is backed with a JDBC connection pool.
 *
 * @author Alex Leigh
 * @since 1.0
 */
public class JDBCTransactionFactory implements TransactionFactory {
    private final ComboPooledDataSource cpds;
    private final PostgresDialect dialect;

    public JDBCTransactionFactory(String schemaPrefix, String jdbcUrl, String jdbcUser, String jdbcPassword) {
        cpds = new ComboPooledDataSource();
        cpds.setJdbcUrl(jdbcUrl);
        cpds.setUser(jdbcUser);
        cpds.setPassword(jdbcPassword);

        // Optional Settings
        cpds.setInitialPoolSize(5);
        cpds.setMinPoolSize(5);
        cpds.setAcquireIncrement(5);
        cpds.setMaxPoolSize(20);
        cpds.setMaxStatements(100);

        dialect = new PostgresDialect(schemaPrefix);
    }


    @Override
    public Transaction makeTransaction() throws SQLException {
        return new JDBCTransaction(cpds.getConnection(), dialect);
    }
}
