package com.fp.armas.rules.query.webservices;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import com.fp.armas.rules.query.webservices.util.ColaImpresionUtil;
import com.fp.common.logger.APPLogger;
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;
import com.fp.persistence.parmas.dto.ws.ColaImpresionDto;
import com.fp.persistence.parmas.inte.TarmColadeImpresion;
import com.fp.persistence.parmas.param.TarmCentroControl;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;

/**
 * Componente que realiza la b&uacute;squedas de los datos de impresi&oacute;n de un usuario
 *
 * @author dcruz
 *
 */
public class ColaImpresion extends QueryRule {

    private static final long serialVersionUID = -3993166768741911054L;
    private static final String QUERY_USUARIO_ID = "SELECT o FROM TsafeUserDetail o WHERE o.pk.usercode=:usercode AND o.pk.dateto=:dateto";
    private static final String QUERY_COLA_IMPRESION = "SELECT o.cdocumento, o.estadoimpresion, o.estadoimpresioncode, o.cimpresion, o.fechaimpresion, o.fecharegistro, o.codigotarjeta"
            + " FROM TarmColadeImpresion o"
            + " inner join tarmdocumentohabilitante i on o.cdocumento = i.cdocumento"
            + " inner join tarmsolicituddocumento n on n.cdocumento = o.cdocumento"
            + " inner join tarmsolicitud k on i.csolicitud = k.csolicitud"
            + " WHERE o.estadoimpresion=:estado  and i.ccentrocontrol = :ccentrocontrol and coalesce(k.estado,'APB') IN ('APB','FIN')";

    @SuppressWarnings("unchecked")
    @Override
    public QueryRequest process(QueryRequest pRequest) throws Exception {
        Query query;
        List<ColaImpresionDto> lcolaImpresion = null;
        try {
            String estado = (String) pRequest.get("estado");
            String usercode = (String) pRequest.get("usercode");
            System.out.println("estado..." + estado);
            System.out.println("usercode..." + usercode);
            query = PersistenceHelper.getEntityManager().createQuery(QUERY_USUARIO_ID);
            query.setParameter("usercode", usercode);
            query.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
            List<TsafeUserDetail> ltsafeUserDetails = query.getResultList();
            TsafeUserDetail tsafeUserDetail;
            if (ltsafeUserDetails != null && !ltsafeUserDetails.isEmpty()) {
                tsafeUserDetail = ltsafeUserDetails.iterator().next();
            } else {
                return pRequest;
            }
            //centro control
            query = PersistenceHelper.getEntityManager().createQuery("select o from TarmCentroControl o"
                    + " where o.pk=(select p.ccentrocontrol from TarmCentroControlJur p "
                    + " where p.provincecode=(select pr.provincecode from TcustPersonAddress pr "
                    + " where pr.pk.personcode=:personcode and"
                    + " pr.pk.dateto=:dateto and"
                    + " pr.principal='Y' and"
                    + " pr.pk.addressnumber=(select max(q.pk.addressnumber) from TcustPersonAddress q "
                    + " where q.pk.personcode=:personcode and"
                    + " q.pk.dateto=:dateto and"
                    + " q.principal='Y')))");
            query.setParameter("personcode", tsafeUserDetail.getPk().getPersoncode());
            query.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
            List<TarmCentroControl> tarmCentroControls = query.getResultList();
            TarmCentroControl tarmCentroControl;
            if (tarmCentroControls != null && !tarmCentroControls.isEmpty()) {
                tarmCentroControl = tarmCentroControls.iterator().next();
            } else {
                return pRequest;
            }
            query = PersistenceHelper.getEntityManager().createNativeQuery(QUERY_COLA_IMPRESION);
            query.setParameter("estado", estado);
            query.setParameter("ccentrocontrol", tarmCentroControl.getPk());
            System.err.println("=============>>>   QUERY EJECUTAR | " + estado + " | " + tarmCentroControl.getPk());
            List<TarmColadeImpresion> coladeImpresionList = new ArrayList<>();
            List<Object[]> ltarmColadeImpresionsTMP = query.getResultList();
            for (Object[] tmp : ltarmColadeImpresionsTMP) {
                TarmColadeImpresion colaImpresionObj = new TarmColadeImpresion();
                colaImpresionObj.setCdocumento(((BigDecimal) tmp[0]).longValue());
                colaImpresionObj.setEstadoimpresion(tmp[1].toString());
                colaImpresionObj.setEstadoimpresioncode(tmp[2].toString());
                colaImpresionObj.setPk(tmp[3].toString());
                colaImpresionObj.setFechaimpresion(tmp[4] == null ? null : (Timestamp) tmp[4]);
                colaImpresionObj.setFecharegistro(tmp[5] == null ? null : (Date) tmp[5]);
                if (tmp[6] != null) {
                    colaImpresionObj.setCodigotarjeta(tmp[6].toString());
                }
                coladeImpresionList.add(colaImpresionObj);
            }
            lcolaImpresion = ColaImpresionUtil.getInstancia().completaColaImpresion(coladeImpresionList, tsafeUserDetail.getPk().getPersoncode(), tsafeUserDetail.getPk().getUsercode());
            pRequest.getResponse().put("COLAIMPRESION", lcolaImpresion);
        } catch (Throwable e) {
            APPLogger.getLogger().error(e.getMessage(), e);
        }
        return pRequest;
    }

}
