package de.hsadmin.core.model.onetier;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class PersistenceManager {

	private static PersistenceManager instance;
	
	private Map<String, EntityManagerFactory> persistenceUnits;
	
	public static EntityManager getEntityManager(String persistUnitName) {
		EntityManagerFactory emf = PersistenceManager.getInstance().getEMF(persistUnitName);
		return emf.createEntityManager();
	}

	public static void close() {
		getInstance().closeFactories();
	}

	private PersistenceManager() {
		persistenceUnits = new HashMap<String, EntityManagerFactory>();
	}

	private EntityManagerFactory getEMF(String persistUnitName) {
		EntityManagerFactory emf = persistenceUnits.get(persistUnitName);
		if (emf == null) {
			emf = Persistence.createEntityManagerFactory(persistUnitName);
			persistenceUnits.put(persistUnitName, emf);
		}
		return emf;
	}

	private static PersistenceManager getInstance() {
		if (instance == null) {
			instance = new PersistenceManager();
		}
		return instance;
	}

	private void closeFactories() {
		for (String puName : persistenceUnits.keySet()) {
			System.out.println("Persistence Unit: " + puName);
			EntityManagerFactory emf = persistenceUnits.get(puName);
			emf.close();
			persistenceUnits.remove(puName);
		}
	}
}
