package com.fp.sessionbeans.helper;

import com.fp.common.helper.Constant;
import com.fp.common.logger.APPLogger;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.PersistenceManager;
import com.fp.persistence.commondb.data.SessionData;
import com.fp.persistence.commondb.data.ThreadFacade;
import com.fp.persistence.pgeneral.seq.TgeneSequences;

public class SequenceThread extends Thread {

    private final Sequence sequence;

    private final Integer company;

    private final String sequencecode;

    public SequenceThread(Sequence sequence, Integer pCompany, String pSequenceCode) {
        this.sequence = sequence;
        this.sequencecode = pSequenceCode;
        this.company = pCompany;
    }

    @Override
    public void run() {
        try {
            SessionData s = new SessionData();
            s.setCompany(this.company);
            ThreadFacade.setSaveRequest(s);
            PersistenceHelper.setEntityManager(PersistenceManager.getInstance().createEntityManagerLocal());
            PersistenceHelper.beginNewTransaction();
            TgeneSequences tgeneSequences = TgeneSequences.findWithLock(PersistenceHelper.getEntityManager(), this.sequencecode);
            tgeneSequences.setCurrentvalue(tgeneSequences.getCurrentvalue() + tgeneSequences.getIncrease());
            if (Constant.ifYes(tgeneSequences.getCyclic())) {
                if (tgeneSequences.getCurrentvalue().compareTo(tgeneSequences.getLastvalue()) >= 0) {
                    tgeneSequences.setCurrentvalue(tgeneSequences.getInitialvalue());
                }
            }
            this.sequence.setNextvalue(tgeneSequences.getCurrentvalue());
            // update del registro
            PersistenceHelper.getEntityManager().merge(tgeneSequences);
          //  Integer.valueOf(tgeneSequences.getCurrentvalue().toString());
            PersistenceHelper.commitNewTransaction();
        } catch (Exception e) {
            APPLogger.getLogger().warn(e, e);
            PersistenceHelper.rollbackNewTransaction();
        } finally {
            PersistenceHelper.closeSession();
        }
    }
}
