package com.fp.general.templates.query;

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;

/**
 *Clase para presentar las plantillas ingresadas
 * @author BPTWPA
 */
public class QueryTemplatesDesc extends QueryRule {

    private static final long serialVersionUID = 1L;
    private static final String JPQL_TEMPLATES = "select d.pk.code, t.description, d.pk.languagecode, d.description "
            + "from TgeneMessageTemplatesDesc d, TgeneMessageTemplates t "
            + "where d.pk.code=t.pk ";

    @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("TGENEMESSAGETEMPLATEDESC");
        List<QueryCriteria> lcriteria = qb.getCriteria();
        EntityManager em = PersistenceHelper.getEntityManager();
        jpql.append(QueryTemplatesDesc.JPQL_TEMPLATES);
        Query qry = em.createQuery(QueryTemplatesDesc.addSimpleCriteriaJPQL(jpql, lcriteria, qb));
        QueryTemplatesDesc.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_code", obj[0]);
                mapResp.put("descmessage", obj[1]);
                mapResp.put("pk_languagecode", obj[2]);
                mapResp.put("description", obj[3]);
                mapResp.put("template", null);
                listResp.add(mapResp);
            }
        }
        response.put("TGENEMESSAGETEMPLATEDESC", listResp);
        return pQueryRequest;
    }

    /**
     * Metodo que agrega los parametros de una consulta jpql
     * @param jpql Creado
     * @param lcriteria Criterios de consulta
     * @return String del jpql
     */
    public static 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);
    }

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