/*
 * 
 */
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.DtoQuery;
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;
import com.fp.persistence.commondb.helper.FormatDates;

// TODO: Auto-generated Javadoc
/**
 * Clase que se encarga de presentar las transactiones que estan en vuelo en la TGENETRANSACTIONLOG.
 * 
 * @author jarias
 */
public class TransactionLogResults extends QueryRule {

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

    /**
     * Metodo que presenta las 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();

        StringBuilder jpql = new StringBuilder(300);
        jpql.append("select t.usercode,t.terminalcode,t.duration," + " t.realdate as time,t.aditionaldata,o.processid,o.sessionid,t.solicitudenumber "
                + " from TgeneTransactionLog t ,TbpmProcessInstance o"
                + " where t.pk in (select i.pk from TbpmProcessInstance i where coalesce(i.finalized, 'N')='N')" + " and t.pk = o.pk ");
        Query qry = null;
        if (qr.isJsf()) {
            DtoQuery dto = qr.getQueryTables().get("TRANSACTIONLOG");
            GeneralQuery.addParametersJSF(jpql, dto, false);
            jpql.append(" order by t.realdate desc");
            qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
            GeneralQuery.setParametersJSF(jpql, dto, qry);
        } else {
            QueryBean qb = (QueryBean) qr.get("TRANSACTIONLOG");
            Map<String, Object> criteria = new HashMap<String, Object>();
            GeneralQuery.addParameters(qb, jpql, criteria);
            qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
            GeneralQuery.setParameters(qb, criteria, qry);
        }

        List<?> ltransactionLog = qry.getResultList();
        List<Map<String, Object>> detailgrid = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < ltransactionLog.size(); i++) {
            Map<String, Object> detail = new HashMap<String, Object>();
            Object[] datos = (Object[]) ltransactionLog.get(i);
            detail.put("usercode", datos[0]);
            detail.put("name", this.consulta(datos[0].toString()));
            detail.put("terminalcode", datos[1]);
            detail.put("duration", datos[2]);
            detail.put("time", datos[3]);
            detail.put("aditionaldata", datos[4]);
            detail.put("processid", datos[5]);
            detail.put("sessionid", datos[6]);
            detail.put("solicitudenumber", datos[7]);
            detailgrid.add(detail);
        }
        response.put("TRANSACTIONLOG", detailgrid);
        return qr;
    }

    /**
     * Metodo que me retorna el nombre de usuario.
     * 
     * @param usercode the usercode
     * @return nombre del usuario
     * @throws Exception la exception
     */
    private String consulta(String usercode) throws Exception {
        javax.persistence.Query qr = PersistenceHelper.getEntityManager().createQuery(TransactionLogResults.SQL);
        qr.setParameter("usercode", usercode);
        qr.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
        return (String) qr.getSingleResult();

    }

    /** Sentencia que consulta el nombre del usuario. */
    public static final String SQL = "select a.name from TcustPersonDetail a ,TsafeUser b" + " where a.pk.personcode = b.personcode"
            + " and b.pk=:usercode" + " and a.pk.dateto=:dateto";
}
