package jp.sf.amateras.mirage.session;

import java.lang.reflect.Constructor;
import java.util.Properties;

import jp.sf.amateras.mirage.exception.ConfigurationException;
import jp.sf.amateras.mirage.util.IOUtil;
import jp.sf.amateras.mirage.util.StringUtil;

public class SessionFactory {

	private static Session session;

	public synchronized static Session getSession() throws ConfigurationException {
		if(session == null){
			Properties properties = IOUtil.loadProperties("jdbc.properties");
			if(properties != null){
				try {
					String sessionClass = properties.getProperty("session.class");
					if(StringUtil.isEmpty(sessionClass)){
						sessionClass = JDBCSessionImpl.class.getName();
					}

					Class<?> clazz = Class.forName(sessionClass);
					Constructor<?> constructor = clazz.getConstructor(Properties.class);
					session = (Session) constructor.newInstance(properties);

				} catch(Exception ex){
					throw new ConfigurationException(ex);
				}
			} else {
				throw new ConfigurationException("jdbc.properties is not found!");
			}
		}

		return session;
	}

}
