package com.fp.facade.ejb;

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

import com.fp.bpm.actions.QueryAction;
import com.fp.common.logger.APPLogger;
import com.fp.dto.Request;
import com.fp.facade.ejb.helper.BeanHelper;
import com.fp.facadeclient.ejb.FacadeBeanJsfRemote;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.PersistenceManager;

@Stateless(name = "querywithcommitbean")
@TransactionManagement(value = TransactionManagementType.BEAN)
public class QueryWithCommitBean extends BeanHelper implements FacadeBeanJsfRemote {

    /**
     * Metodo que se encarga de la ejecucion de una accion.
     * 
     * @param request Request con los datos necesarios para ejecutar una accion, consulta o mantenimiento.
     * @return Object
     * @throws Exception
     */
    @Override
    public Object process(Request request) throws Throwable {
        this.fillThreadFacade(request.getCompany());
        Object resp = null;
        // Para obtener un EntityManager dinamico
        EntityManager em = PersistenceManager.getInstance().createEntityManagerLocal();
        PersistenceHelper.setEntityManager(em);
        try {
            BeanHelper.cleanThreadLocal();
            PersistenceHelper.beginTransaction();
            QueryAction qa = new QueryAction();
            resp = qa.process(request);
            PersistenceHelper.commitTransaction();
            return resp;
        } catch (Throwable e) {
            APPLogger.getLogger().warn(e, e);
            PersistenceHelper.rollbackTransaction();
            try {
                return BeanHelper.fillError(e);
            } catch (Throwable e1) {
                APPLogger.getLogger().warn(e1, e1);
                throw e1;
            }
        } finally {
            PersistenceHelper.closeSession();
        }
    }

    @Override
    public int executeNativeQuery(String string) {
        throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
    }

}
