package com.fp.general.rules.query.code;

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

import javax.persistence.Query;

import com.fp.common.helper.Constant;
import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.general.exception.GeneralException;
import com.fp.persistence.commondb.GeneralQuery;
import com.fp.persistence.commondb.PersistenceHelper;

/**
 * Clase que se encarga de enviar solo los datos necesarios del cliente
 * 
 * @author scastillo
 */
@SuppressWarnings("serial")
public class LovCustomer extends QueryRule {

    /**
     * JPQL que obtiene informacion de personas
     */
    private static final String JPQL_CUSTOMER = "select t.personcode, persontypecatalog,identification,name,"
            + "     (select cd.description from TgeneCatalogDetail cd " + "           where cd.catalogcode = t.identificationcatalogcode "
            + "           and cd.catalog = t.identificationcatalog " + "     ) as identificationdesc, "
            + "     (select photocode from TcustPeople tp" + "           where tp.personcode = t.personcode "
            + "           and tp.dateto = t.dateto " + "     ) as photocode " + " from TcustPersonDetail t " + " where t.dateto = :dateto ";

    /**
     * Metodo que construye la respuesta solo con los datos necesarios
     * 
     * @param pQueryRequest QueryRequest
     * @return pQueryRequest QueryRequest
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @Override
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        QueryBean qb = (QueryBean) pQueryRequest.get("TCUSTPERSONDETAILLOV");

        String[] resp = CriteriaValidator.validatePercentage(qb);
        if (resp[0].compareTo("0") == 0) {
            throw new GeneralException("GENE-0043", "EL CRITERIO DE BÚSQUEDA --> {0} NO ES SUFICIENTE", resp[1]);
        }

        Map<String, Object> mcriteria = new HashMap<String, Object>();

        StringBuilder jpql = new StringBuilder();
        jpql.append(LovCustomer.JPQL_CUSTOMER);
        GeneralQuery.addParameters(qb, jpql, mcriteria, true);
        Query qry = PersistenceHelper.getEntityManager().createNativeQuery(String.valueOf(jpql));
        qry.setParameter("dateto", Constant.getDefaultExpiryTimestamp());
        GeneralQuery.setParameters(qb, mcriteria, qry);
        List<Object[]> ldata = qry.getResultList();

        List<Map<String, Object>> lfinal = new ArrayList<Map<String, Object>>();
        if ((ldata != null) && (!ldata.isEmpty())) {
            for (Object[] obj : ldata) {
                Map<String, Object> m = new HashMap<String, Object>();
                m.put("pk_personcode", obj[0]);
                m.put("persontypecatalog", obj[1]);
                m.put("identification", obj[2]);
                m.put("name", obj[3]);
                m.put("identificationdesc", obj[4]);
                m.put("photocode", obj[5]);
                lfinal.add(m);
            }
        } else {
            if (qb.getPage() == 1) {
                Map<String, Object> m = new HashMap<String, Object>();
                m.put("pk_personcode", null);
                m.put("persontypecatalog", null);
                m.put("identification", null);
                m.put("name", null);
                m.put("identificationdesc", null);
                m.put("photocode", null);
                lfinal.add(m);
            }
        }

        pQueryRequest.getResponse().put("TCUSTPERSONDETAILLOV", lfinal);

        return pQueryRequest;
    }
}
