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

import java.math.BigDecimal;

import javax.persistence.Query;

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

/**
 * Clase que se encarga de consultar la secuencia correspondiente al usuario
 * 
 * @author scastillo
 */
public class AddressSequence extends QueryRule {

    @Override
    public QueryRequest process(QueryRequest qr) throws Exception {
        Integer personcode = null;
        Object personcodeObj = qr.get("personcode");
        if (personcodeObj instanceof Integer) {
            personcode = qr.getInteger("personcode");
        } else if (personcodeObj instanceof String) {
            personcode = Integer.valueOf(qr.getString("personcode"));
        }
        Query qry = PersistenceHelper.getEntityManager().createQuery(
                "select coalesce(max(tcpa.pk.addressnumber), 0) from TcustPersonAddress tcpa where tcpa.pk.personcode = :personcode");
        qry.setParameter("personcode", personcode);
        Object test = qry.getSingleResult();
        Integer result = null;
        if (test instanceof Integer) {
            result = (Integer) test;
        } else if (test instanceof BigDecimal) {
            result = ((BigDecimal) test).intValueExact();
        }
        qr.getResponse().put("result", test);
        return qr;
    }
}
