package gov.va.vinci.dart.db.util;

import java.util.Hashtable;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

public class HibernateSessionManagerImpl implements ISessionManager {

	private static EntityManagerFactory emf;
	
	private static Hashtable<Thread, EntityManager> SESSION_HASH = new Hashtable<Thread, EntityManager>();

//	static {
//		try {
//			emf = Persistence.createEntityManagerFactory("manager1");
//		} catch (Throwable ex) {
//			// Make sure you log the exception, as it might be swallowed
//			System.err.println("Initial SessionFactory creation failed." + ex);
//			ex.printStackTrace();
//			throw new ExceptionInInitializerError(ex);
//		}
//	}

	public static EntityManagerFactory getEntityManagerFactory() {
		return emf;
	}

    /**
     * Method called by HibernateSessionManagerProcessor.
     *
     * @param entityManagerFactory
     */
    public static void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        emf = entityManagerFactory;
    }

    @Override
	public EntityManager findEntityManagerForThread() {

		EntityManager mgr = SESSION_HASH.get(Thread.currentThread());

		if (mgr == null) {
			mgr = emf.createEntityManager();
			SESSION_HASH.put(Thread.currentThread(), mgr);
			mgr.getTransaction().begin();
		}

		return mgr;
	}

	@Override
	public void closeEntityManagerForThread() {
		EntityManager mgr = SESSION_HASH.get(Thread.currentThread());

		if (mgr != null) {
			EntityTransaction transaction = mgr.getTransaction();
			
			if (transaction.isActive() == true
					&& transaction.getRollbackOnly() == false) {
				mgr.getTransaction().commit();
			}
			
			mgr.close();
		}

		SESSION_HASH.remove(Thread.currentThread());
	}

	@Override
	public void rollbackEntityManagerForThread() {
		EntityManager mgr = SESSION_HASH.get(Thread.currentThread());

		if (mgr != null) {
			mgr.getTransaction().rollback();
		}
	}

}
