/*
 * 
 */
package com.fp.bpmlib.query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import com.fp.dto.Response;
import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.GeneralQuery;
import com.fp.persistence.commondb.PersistenceHelper;

// TODO: Auto-generated Javadoc
/**
 * Clase que se encarga de presentar en el lov las transacciones que contiene la tabla TgeneTransactionLog.
 * 
 * @author jarias
 */
public class TransactionsLog extends QueryRule {

    /** Constante serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /**
     * Metodo que presenta la lista de transacciones en vuelo.
     * 
     * @param qr the qr
     * @return query request
     * @throws Exception la exception
     */
    @Override
    public QueryRequest process(QueryRequest qr) throws Exception {
        Response response = qr.getResponse();
        QueryBean qb = (QueryBean) qr.get("TGENETRANSACTION");
        StringBuilder jpql = new StringBuilder(400);
        jpql.append("select t.pk.transactionmodule,t.pk.transactioncode,t.pk.transactionversion,t.name "
                + "from TgeneTransaction t where exists (  select  1 "
                + "from TgeneTransactionLog r  where exists(select 1 from TbpmProcessInstance o "
                + "where o.pk = r.pk and coalesce(o.finalized, 'N')='N') and t.pk.transactionmodule=r.transactionmodule "
                + "and t.pk.transactioncode=r.transactioncode and t.pk.transactionversion=r.transactionversion ) ");
        Map<String, Object> criteria = new HashMap<String, Object>();
        GeneralQuery.addParameters(qb, jpql, criteria);
        Query qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
        GeneralQuery.setParameters(qb, criteria, qry);
        List<?> ltransaction = qry.getResultList();
        List<Map<String, Object>> detailgrid = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < ltransaction.size(); i++) {
            Map<String, Object> detail = new HashMap<String, Object>();
            Object[] datos = (Object[]) ltransaction.get(i);
            detail.put("pk_transactionmodule", datos[0]);
            detail.put("pk_transactioncode", datos[1]);
            detail.put("pk_transactionversion", datos[2]);
            detail.put("name", datos[3]);
            detailgrid.add(detail);
        }
        if (ltransaction.isEmpty()) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("pk_transactionmodule", "");
            detail.put("pk_transactioncode", "");
            detail.put("pk_transactionversion", "");
            detail.put("name", "");
            detailgrid.add(detail);
        }
        response.put("TGENETRANSACTION", detailgrid);
        return qr;
    }
}
