package vut.msa;


import org.apache.log4j.Logger;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Trieda Hibernate Utility, ktora sluzi na vytvorenie relacie s databazou.
 */
public class BackupHibernateUtil {

    private static final SessionFactory sessionFactory;
    public static final ThreadLocal session = new ThreadLocal();
    private static final Logger log = Logger.getLogger(BackupHibernateUtil.class);

    /**
     * Statický blok, ktorý nahrá konfiguráciu Hibernate a vytvorí továrnu na
     * relácie Hibernate.
     */
    static {
        try {
            // Vytvorenie SessionFactory z konifguracneho suboru (hibernate.cfg.xml)
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            log.error("Inicializacia toverne na relacie Hibernate zlyhala." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * Metoda vrati objekt SessionFactory, ktory vytvara relacie Hibernate.
     *
     * @return tovarna na relacie
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * Metoda vrati aktualnu vytvorenu relaciu Hibernate.
     * @return
     * @throws HibernateException chyba, pri ziskavani relacie
     */
    public static Session currentSession() throws HibernateException {

        Session s = (Session) session.get();
        if (s == null){

            // TO DO: getCurrentSession ide iba pri implementacii JTA, doriesit na Tomcat
            s = sessionFactory.openSession();
            
            session.set(s);
            s.setFlushMode(FlushMode.MANUAL);
        }

        return s;

    }

    /**
     * Metoda zatvori aktualnu relaciu Hibernate.
     *
     * @throws HibernateException chyba, pri zatvarani relacie
     */
    public static void closeSession() throws HibernateException {

        Session s = (Session) session.get();
        if (s != null){
            s.flush();
            s.close();
        }

        session.set(null);
    }

    /**
     * Metoda uzatvara tovaren (SessionFactory) na relacie Hibernate.
     */
    public static void shutdown() {
        getSessionFactory().close();
    }
}
