package id.iptek.utms.agent.db;

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

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Jaka Ramdani
 */
public class DBConn {

    private static Logger logger = LoggerFactory.getLogger(DBConn.class);
    
    private boolean isUseDatasource;
    private String datasource;
    private String driver;
    private String url;
    private String username;
    private String password;
    private static DBConn self;

    private DBConn() {
    }

    public void init(String datasource) throws Exception {
        this.datasource = datasource;
        logger.debug("Using Data Source: {}", this.datasource);
        this.isUseDatasource = true;
    }
    
    public void init(String driver, String url, String username, String password) throws Exception {
    	this.driver = driver;
    	this.url = url;
    	this.username = username;
    	this.password = password;
    	
    	//load driver
        logger.debug("Load JDBC driver: {}", this.driver);
    	Class.forName(this.driver);
    }

    public Connection getConnection() throws SQLException {
        if(!isUseDatasource) {
            return DriverManager.getConnection(url, username, password);
        } else {
            try {
                InitialContext initialContext = new InitialContext();
                DataSource dataSource = (DataSource) initialContext.lookup(this.datasource);
                return dataSource.getConnection();
            } catch(NamingException ex) {
                throw new SQLException("Naming Exception when getting connection from datasource: {}", this.datasource, ex);
            }
        }
    }

    public static DBConn getInstance() {
        if (self == null) {
            self = new DBConn();
        }
        return self;
    }
}
