package com.fp.sessionbeans.ejb;

import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import com.fp.common.helper.Constant;
import com.fp.persistence.pgeneral.seq.TgeneSequences;
import com.fp.sessionbeans.ejb.interfaces.SequenceBeanLocal;

/**
 * Session Bean que entrega el nuemero de secuenia, dado un codigo de secuencia.
 * 
 * @author Jorge Vaca.
 * @version 2.1
 */
@Stateless
@TransactionManagement(value = TransactionManagementType.BEAN)
public class SequenceBean implements SequenceBeanLocal {
    /**
     * Metodo que entrega el valor de uan secuencia, dado el codigo de sequencia.
     * 
     * @param pSequenceCode Codigo de secuencia a obtener el numero de secuenia.
     * @return Integer
     * @throws Exception
     */
    @Override
    public Long getNextValueJta(EntityManager em, String pSequenceCode) throws Exception {
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        try {
            Long sec = null;
            TgeneSequences tgeneSequences = TgeneSequences.findWithLock(em, pSequenceCode);
            tgeneSequences.setCurrentvalue(tgeneSequences.getCurrentvalue() + tgeneSequences.getIncrease());
            if (Constant.ifYes(tgeneSequences.getCyclic())) {
                if (tgeneSequences.getCurrentvalue().compareTo(tgeneSequences.getLastvalue()) >= 0) {
                    tgeneSequences.setCurrentvalue(tgeneSequences.getInitialvalue());
                }
            }
            // update del registro
            em.merge(tgeneSequences);
            sec = Long.valueOf(tgeneSequences.getCurrentvalue().toString());
            tx.commit();
            return sec;
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }
            throw e;
        } finally {
            try {
                if (em.isOpen()) {
                    em.clear();
                    em.close();
                }
            } catch (Exception e) {
                throw e;
            }
        }

    }

}
