package vut.msa.helpers;

import java.io.Serializable;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import vut.msa.BackupHibernateUtil;

/**
 * Abstraktna trieda Helper, ktoru dedia triedy typu Helper. Tato trieda je zodpovedna
 * za vytvorenie spojenia s databazou, zacatia a ukoncenia transakcie.
 */
public abstract class Helper implements Serializable {

    protected static final transient Logger log = Logger.getLogger(Helper.class);
    protected Session session;

    protected SessionFactory factory;
    
    public Helper() {
        factory = BackupHibernateUtil.getSessionFactory();
        session = BackupHibernateUtil.currentSession();
    }

    /**
     * Metoda zacne transakciu v aktualnej relacii Hibernate.
     */
    public void openSession() {

        if (!session.getTransaction().isActive()) {
            session.beginTransaction();
        }
    }

    /**
     * Metoda ukonci transakciu v aktualnej relacii Hibernate.
     *
     * @param transaction transakcia, ktora ma byt ukoncena
     * @param commit true, ak je treba vykonat potvrdenie (commit); false, ak netreba.
     */
     public synchronized void endTransaction(Transaction transaction, boolean commit){

         session.flush();
         session.clear();
         
         if (transaction.isActive()){
             if (commit){
                 if (!transaction.wasCommitted()){
                     transaction.commit();
                 }
             } else{
                 if(!transaction.wasRolledBack()){
                     transaction.rollback();
                     log.info("Vraciam spat transakciu!");
                 }
             }
         }
     }
}
