/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fp.bpmlib.query.rules;

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

import javax.persistence.EntityManager;
import javax.persistence.Query;

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

// TODO: Auto-generated Javadoc
/**
 * Clase que realiza la consulta las reglas BPM.
 * 
 * @author BPTWPA
 */
public class Rules extends QueryRule {

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

    /** Constante JPQL_RULES. */
    private static final String JPQL_RULES = "select r.pk.rulecode, r.pk.companycode, r.description, r.packagename, "
            + "r.snapshot, r.active, r.refresh, r.parametertype, r.messagecode , m.description " + "from TbpmRules r, TgeneMessageTemplates m "
            + "where r.messagecode=m.pk ";

    /**
     * Process.
     * 
     * @param pQueryRequest the query request
     * @return query request
     * @throws Exception la exception
     */
    @Override
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        StringBuilder jpql = new StringBuilder();
        List<Map<String, Object>> listResp = new ArrayList<Map<String, Object>>();
        Response response = pQueryRequest.getResponse();
        QueryBean qb = (QueryBean) pQueryRequest.get("TBPMRULES");
        List<QueryCriteria> lcriteria = qb.getCriteria();
        EntityManager em = PersistenceHelper.getEntityManager();
        jpql.append(Rules.JPQL_RULES);
        Query qry = em.createQuery(this.addSimpleCriteriaJPQL(jpql, lcriteria, qb));
        this.setSimpleParametersJPQL(qry, lcriteria);
        qry.setFirstResult((qb.getPage() - 1) * qb.getPageSize());
        qry.setMaxResults(qb.getPageSize());
        @SuppressWarnings("unchecked")
        List<Object> list = qry.getResultList();
        if (!list.isEmpty()) {
            for (Object oj : list) {
                Map<String, Object> mapResp = new HashMap<String, Object>();
                Object[] obj = (Object[]) oj;
                mapResp.put("pk_rulecode", obj[0]);
                mapResp.put("pk_companycode", obj[1]);
                mapResp.put("description", obj[2]);
                mapResp.put("packagename", obj[3]);
                mapResp.put("snapshot", obj[4]);
                mapResp.put("active", obj[5]);
                mapResp.put("refresh", obj[6]);
                mapResp.put("parametertype", obj[7]);
                mapResp.put("messagecode", obj[8]);
                mapResp.put("descmessage", obj[9]);
                listResp.add(mapResp);
            }
        }
        response.put("TBPMRULES", listResp);
        return pQueryRequest;
    }

    /**
     * M�todo que agrega los parametros de una consulta jpql.
     * 
     * @param jpql Creado
     * @param lcriteria Criterios de consulta
     * @param qb the qb
     * @return String del jpql
     */
    private String addSimpleCriteriaJPQL(StringBuilder jpql, List<QueryCriteria> lcriteria, QueryBean qb) {
        for (QueryCriteria obj : lcriteria) {
            if (obj.getValue() != null) {
                jpql.append(" and ").append(obj.getProperty()).append(" ").append(obj.getOperation()).append(" :")
                        .append(obj.getProperty().replace(".", ""));
            }
        }
        boolean first = true;
        for (QueryCriteria order : qb.getOrder(true)) {
            if (first) {
                jpql.append(" ORDER BY ");
            } else {
                jpql.append(" asc, ");
            }
            jpql.append(order.getProperty());
            first = false;
        }
        return String.valueOf(jpql);
    }

    /**
     * M�todo que setea los parametros para la consulta.
     * 
     * @param qry Query
     * @param lcriteria Criterios de consluta
     */
    private void setSimpleParametersJPQL(Query qry, List<QueryCriteria> lcriteria) {
        for (QueryCriteria obj : lcriteria) {
            if (obj.getValue() != null) {
                qry.setParameter(obj.getProperty().replace(".", ""),
                        ((obj.getProperty().replace(".", "").compareTo("rpkcompanycode") == 0) ? Integer.valueOf(String.valueOf(obj.getValue()))
                                : obj.getValue()));
            }
        }
    }
}
