package com.fp.bpmlib.query.groups;

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

import javax.persistence.Query;

import com.fp.dto.query.QueryBean;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;

/**
 * Lista de Valores de Usuarios
 * 
 * @author gfiallos
 * 
 */
public class UserLov extends QueryRule {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * Consulta
     */
    private static final String SQL = "select u.usercode, (select d.name from tcustpersondetail d where d.dateto=u.dateto and d.personcode=u.personcode)"
            + " from tsafeuserdetail u where u.isuserbpm='Y' and u.dateto=:dateto and not exists( "
            + " select 1 from tbpmgroupsusers i where i.companycode=:cia and i.groupcode=:group and i.usercode=u.usercode)";

    @Override
    public QueryRequest process(QueryRequest pRequest) throws Exception {
        QueryBean qb = (QueryBean) pRequest.get("TSAFEUSERDETAILLOV");
        Query qry = PersistenceHelper.createNativeQuery(UserLov.SQL);
        qry.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
        qry.setParameter("cia", pRequest.getCompany());
        qry.setParameter("group", qb.getCriteriaValue("group"));
        @SuppressWarnings("unchecked")
        List<Object[]> l = qry.getResultList();
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for (Object[] objects : l) {
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("pk_usercode", objects[0]);
            m.put("name", objects[1]);
            data.add(m);
        }
        pRequest.getResponse().put("TSAFEUSERDETAILLOV", data);
        return pRequest;
    }

}
