package org.jerrymouse.database.hadoop.jpa;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HadoopPersistenceProvider implements PersistenceProvider {
	Log log = LogFactory.getLog(HadoopPersistenceProvider.class);

	Map<String, String> config(String persistenceUnitName) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			log.debug("Look up for persistence unit: " + persistenceUnitName);
			Enumeration<URL> xmls;
			xmls = Thread.currentThread().getContextClassLoader().getResources(
					"META-INF/persistence.xml");

			if (!xmls.hasMoreElements()) {
				log
						.info("Could not find any META-INF/persistence.xml file in the classpath");
			}
			while (xmls.hasMoreElements()) {
				URL url = xmls.nextElement();
				log.trace("Analysing persistence.xml:" + url);
				Map<String, String> t = PersistenceXMLReader.read(
						persistenceUnitName, url);
				if (t != null)
					map.putAll(t);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	public EntityManagerFactory createContainerEntityManagerFactory(
			PersistenceUnitInfo info, Map map) {
		return null;
	}

	public EntityManagerFactory createEntityManagerFactory(
			String persistenceUnitName, Map overridenProperties) {
		Map properties = config(persistenceUnitName);
		if (overridenProperties != null)
			properties.putAll(overridenProperties);
		EntityManagerFactory entityManagerFactory = new HadoopEntityManagerFactory(
				properties);
		return entityManagerFactory;
	}
}
