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;
import com.fp.persistence.commondb.exception.CommondbException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.persistence.Query;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import org.hibernate.HibernateException;

/**
 * Ejb, que actua como fachada de transacciones de consulta.
 * 
 * @author Jorge Vaca.
 * @version 2.1
 */
@Stateless(name = "querybean")
@TransactionManagement(value = TransactionManagementType.BEAN)
public class QueryBean 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 {
                System.err.println("===========> ERROR " + e);
                return BeanHelper.fillError(e);
            } catch (Throwable e1) {
                APPLogger.getLogger().warn(e1, e1);
                throw e1;
            }
        } finally {
            PersistenceHelper.closeSession();
        }
    }

    @Override
    public int executeNativeQuery(String query) {
        int f = 0;
        try {
            EntityManager em = PersistenceManager.getInstance().createEntityManagerLocal();
            PersistenceHelper.setEntityManager(em);
            PersistenceHelper.beginTransaction();
            Query q = em.createNativeQuery(query);
            f = q.executeUpdate();
            PersistenceHelper.commitTransaction();

        } catch (Throwable e) {
                        PersistenceHelper.rollbackTransaction();

            Logger.getLogger(QueryBean.class.getName()).log(Level.SEVERE, null, e);
        } finally{
            PersistenceHelper.closeSession();
        }
        return f;
    }

}
