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.report.ReportProcessor;
import com.fp.common.fin.MessageGenerator;
import com.fp.common.logger.APPLogger;
import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.QueryRequest;
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 = "reportbean")
@TransactionManagement(value = TransactionManagementType.BEAN)
public class ReportBean 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);
        Response response = new Response(Response.RESPONSE_OK, "OK");
        try {
            BeanHelper.cleanThreadLocal();
            QueryRequest qr = new QueryRequest();
            request.copy(qr);
            request.copyMapValues(qr);

            qr.setQueryTables(request.getQueryTables());
            qr.setJsf(true);
            qr.setResponse(response);
            qr.putAll(request.getModifiedData()); //campos del request codigo de consuta.
            // fija numero de mensaje
            MessageGenerator mg = MessageGenerator.getInstance();
            qr.setJournalId(mg.generateId(qr.getUser()));

            PersistenceHelper.beginTransaction();
            ReportProcessor rp = new ReportProcessor();
            resp = rp.process(qr);
            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
    }


}
