package dendrarium.commandline;

import java.util.HashMap;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.context.ManagedSessionContext;

/**
 *
 * @author pta
 */
public class CommandLineHU {

    private static SessionFactory sessionFactory;

    private static Map<String, String> properties = new HashMap();

    public static void setProperty(String k, String v) {
        properties.put(k, v);
    }

    private static void init() {
        try {
            Configuration cfg = new AnnotationConfiguration().configure("hibernate-commandline.cfg.xml");

            for (String k : properties.keySet()) {
                cfg.setProperty(k, properties.get(k));
            }

            sessionFactory = cfg.buildSessionFactory();
            ManagedSessionContext.bind(sessionFactory.openSession());
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            init();
        }
        return sessionFactory;
    }

    public static Session getCurrentSession() {
        /* XXX */
        return getSessionFactory().openSession();
    }
}
