/**
 * 
 */
package kr.co.kihyun.beans.entity.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;

import kr.co.kihyun.moumi.MoumiConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author bhs
 * 
 */
public final class PMF {
	private static final Logger LOG = LoggerFactory.getLogger(PMF.class);
	private static HashMap<Object, PersistenceManagerFactory> pmfTable = new HashMap<Object, PersistenceManagerFactory>();

	private PMF() {
	}

	public static PersistenceManagerFactory get() {
		PersistenceManagerFactory pmf = null;
		if ((pmf = pmfTable.get(null)) == null) {
			try {
				PMF.set(JDOHelper.getPersistenceManagerFactory(MoumiConfig.getPmfProperties()));
			} catch (Exception e) {		
				// if unable to initialize static block.
				
                //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 : Update by YOUNGJUN,CHO
                /*
                Properties properties = new Properties();
				InputStream stream = MoumiConfig.class.getResourceAsStream("/moumi-pmf.properties");
				try {
					properties.load(stream);
					PMF.set(JDOHelper.getPersistenceManagerFactory(properties));
				} catch (Exception e1) {
					throw new RuntimeException(e1);
				}
                */
                            
                Properties properties = null;
                InputStream stream = null;
                try {
                    properties = new Properties();
                    stream = MoumiConfig.class.getResourceAsStream("/moumi-pmf.properties");
                    properties.load(stream);
                    PMF.set(JDOHelper.getPersistenceManagerFactory(properties));
                } catch (IOException ioex) {
                    ioex.printStackTrace();
                } catch (Exception e1) {
					throw new RuntimeException(e1);
				}
                //================================================
			} finally {
				pmf = pmfTable.get(null);
			}
		}
		return pmf;
	}

	public static PersistenceManagerFactory get(Object key) {
		return pmfTable.get(key);
	}

	public static void set(PersistenceManagerFactory pmf) {
		pmfTable.put(null, pmf);
	}

	public static void set(Object key, PersistenceManagerFactory pmf) {
		pmfTable.put(key, pmf);
		LOG.debug("set pmf({}) for key({})", new Object[] { pmfTable.get(key), key });
	}

}
