package hibergui.hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class SessionManager {
	
	private SessionFactory sf;
	private Session session;
	
	private SessionManager(Configuration conf) {
		sf = conf.buildSessionFactory();
		session = sf.openSession();
	}
	
	public Session getSession() {
		return session;
	}
	
	public void close() {
		session.close();
		sf.close();
	}
	
	// Singleton:
	
	private static SessionManager instance;
	
	public static void initialize() {
		assert(instance == null);
		instance = new SessionManager(new Configuration().configure());
	}
	
	public static void initialize(String confFile) {
		assert(instance == null);
		instance = new SessionManager(new Configuration().configure(confFile));
	}
	
	public static void initialize(Configuration conf) {
		assert(instance == null);
		instance = new SessionManager(conf);
	}
	
	public static boolean initialized() {
		return instance != null;
	}

	public static SessionManager instance() {
		assert(instance != null);
		return instance;
	}

	public static Session session() {
		return instance().session;
	}

	@SuppressWarnings("unchecked")
	public List list(String hql) {
		Transaction trans = session.beginTransaction();
		List result = session.createQuery(hql).list();
		trans.commit();
		return result;
	}
}
