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

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

import com.fp.common.helper.Constant;
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;
import javax.persistence.Query;

/**
 * Clase que realiza la consulta las instituciones financieras y envía los datos
 * necesarios para el lov de Instituciones
 * 
 * @author wpatiño
 */
public class LovFinancialInstitutions extends QueryRule {

	@Override
	public QueryRequest process(QueryRequest qr) throws Exception {
		Response response = qr.getResponse();
		QueryBean qb = (QueryBean) qr.get("TCUSTFINANCIALINSTITUTIONSLOV");
		Map<String, Object> mcriteria = new HashMap<String, Object>();
		StringBuilder jpql = new StringBuilder();		
		jpql.append("select t.personcode,t.name from TcustPersonDetail t where t.personcode in (select f.personcode from TcustFinancialInstitutions f) and t.dateto = :dateto");
		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>> lresp = 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("name", obj[1]);
				lresp.add(m);
			}
		} else {
			if(qb.getPage()==1){
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("pk_personcode", null);			
			m.put("name", null);
			lresp.add(m);
			}
		}

		response.put("TCUSTFINANCIALINSTITUTIONSLOV", lresp);
		return qr;
	}
}
