package pizza.persistence;

import org.hibernate.*;
import org.hibernate.cfg.*;
import java.sql.Connection;

/**
 * Startup Hibernate and provide access to the singleton SessionFactory and a
 * few other important properties
 */
public class HibernateUtil {

	private static SessionFactory sessionFactory;

	private static String jndiName = null;

	private static String hibernateDialect = null;

	private static int isolationLevel = -1;

	static {
		try {
			Configuration cfg = new Configuration();
			sessionFactory = cfg.configure().buildSessionFactory();
			// pick up any JNDI name configured for web app
			// (not needed, null, for a client-server or local app )
			jndiName = cfg.getProperty("hibernate.connection.datasource");
			// this should work for any app
			hibernateDialect = cfg.getProperty("hibernate.dialect");
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		// Alternatively, we could look up in JNDI here
		return sessionFactory;
	}

	public static String getJndiName() {
		return jndiName;
	}

	// 1 = RU, 2 = RC, 4 = RR, 8 = serializable
	public static int getIsolationLevel() {
		try {
			// Set up test connectionto get iso level
			// JDBC connection from Hibernate session
			Session session = sessionFactory.getCurrentSession();
			session.beginTransaction();
			Connection connection = session.connection();
			isolationLevel = connection.getTransactionIsolation();
			session.getTransaction().commit(); // closes this test session

		} catch (Exception ex) {
			throw new RuntimeException("Test connection to database failed", ex);
		}

		return isolationLevel;
	}

	public static String getHibernateDialect() {
		return hibernateDialect;
	}

	public static void shutdown() {
		// Close caches and connection pools
		getSessionFactory().close();
	}
}

