package de.dassit.dbwrapper;

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

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

public class DbTool {
	protected static DataSource dataSource;

	private static String autoincrementType;

	protected static boolean debug = false;

	/**
	 * @return the autoincrementType
	 */
	public String getAutoincrementType() {
		return autoincrementType;
	}

	/**
	 * @param autoincrementType
	 *            the autoincrementType to set
	 */
	public void setAutoincrementType(String autoincrementType) {
		DbTool.autoincrementType = autoincrementType;
	}

	/**
	 * @return true or false for debugging on or off
	 */
	public boolean isDebug() {
		return debug;
	}

	/**
	 * enable/disable debug logging
	 * 
	 * @param debug
	 *            true or false for debugging on or off
	 */
	public void setDebug(boolean debug) {
		DbTool.debug = debug;
	}

	protected static void openDb() {
		try {

			InitialContext cxt = new InitialContext();

			dataSource = (DataSource) cxt
					.lookup("java:/comp/env/jdbc/DbToolDatabase");
			if (dataSource == null) {
				throw new NamingException(
						"Data source jdbc/DbToolDatabase not found");
			}
		} catch (NamingException ex) {
			System.out.println(ex);
			ex.printStackTrace();
		}
	}

	public static void setDataSource(DataSource ds) {
		dataSource = ds;
	}
	
	public static void closeDb() throws SQLException {
		// no longer used
	}

	public static Connection getDb() throws SQLException {
		if (dataSource == null) {
			openDb();
			if (dataSource == null) {
				System.out.println("failed to get data source");
				return null;
			}
		}

		return dataSource.getConnection();
	}

	public static void releaseDb(Connection c) {
		if (c == null)
			return;
		try {
			c.close();
		} catch (SQLException e) {
			System.out.println("error closing connection: " + e.getMessage());
		}
	}

	public boolean ping() {
		// pingCount++;
		Connection c = null;

		try {
			c = getDb();
			Statement s = c.createStatement();
			s.executeQuery("SELECT 1");
			s.close();
		} catch (SQLException ex) {
			debug("SQL ping failed");
			return false;
		} finally {
			releaseDb(c);
		}
		return true;
	}

	public static void debug(String s) {
		if (debug) {
			System.out.println(s);
		}
	}
}
