package com.heckmansoft.surjey.model.datastore;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

/**
 * Abstract and regulate access to DataSource.
 *
 * Based on the "Singleton Pattern".
 */
public class DAO
{
    private final static String JNDI_NAME = "java:/comp/env/jdbc/surjey";
    private static DAO singleton;
    protected DataSource data_source;

    /**
     * Constructor
     * Private access to enforce singleton pattern.
     * Use the getInstance() method instead.
     * @see getInstance()
     * @param data_source
     */
    private DAO(DataSource data_source) {
        this.data_source = data_source;
    }

    /**
     * Retrieve the single DAO instance.
     * @return The DAO
     */
    public static DAO getInstance() {
        Logger log = Logger.getLogger(DAO.class);
        if (DAO.singleton == null) {
            try {
                Context context = new InitialContext();
                DataSource data_source = (DataSource) context.lookup(JNDI_NAME);
                DAO.singleton = new DAO(data_source);
            } catch (NamingException e) {
                throw new RuntimeException(e);
            }
        }
        return DAO.singleton;
    }

    /**
     * Get a new connection to the database.
     * @param autoCommit Enable auto commit
     * @return New connection to the database
     * @throws SQLException
     */
    public Connection getConnection(boolean autoCommit) throws SQLException {
        Connection connection = data_source.getConnection();
        connection.setAutoCommit(autoCommit);
        return connection;
    }
}
