/*
 * 
 */
package com.fp.bpmlib.query;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
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 com.fp.persistence.commondb.helper.APPDates;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pbpm.gene.TbpmProcessInstance;

// TODO: Auto-generated Javadoc
/**
 * Clase que se encarga de presentar las transactiones que estan en vuelo en la TGENETRANSACTIONLOG.
 * 
 * @author gfiallos
 */
public class EndedFlowsResults extends QueryRule {

    /** serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /**
     * Metodo que presenta las transacciones en vuelo.
     * 
     * @param qr the qr
     * @return query request
     * @throws Exception la exception
     */
    @Override
    public QueryRequest process(QueryRequest qr) throws Exception {
        Response response = qr.getResponse();
        
        Query qry = this.prepareQuery(qr);
        
        List<?> ltransactionLog = qry.getResultList();
        List<Map<String, Object>> detailgrid = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < ltransactionLog.size(); i++) {
            Map<String, Object> detail = new HashMap<String, Object>();
            Object[] datos = (Object[]) ltransactionLog.get(i);
            detail.put("solicitudenumber", datos[0]);
            detail.put("usercode", datos[1]);
            // detail.put("terminalcode", datos[1]);
            detail.put("aditionaldata", datos[5]);
            TbpmProcessInstance pi = (TbpmProcessInstance) datos[6];
            detail.put("id", pi.getPk());
            detail.put("init", pi.getCreationdate());
            detail.put("end", pi.getEnddate());
            detail.put("duration",
                    FormatDates.getInstance().getTimeFormat().format(new Date(pi.getEnddate().getTime() - pi.getCreationdate().getTime())));
            detailgrid.add(detail);
        }
        response.put("TRANSACTIONLOG", detailgrid);
        return qr;
    }

    /**
     * Prepare query.
     * 
     * @param qr the qr
     * @return query
     * @throws Exception la exception
     */
    private Query prepareQuery(QueryRequest qr) throws Exception {
        StringBuilder jpql = new StringBuilder(300);
        jpql.append("select t.solicitudenumber, t.usercode,t.terminalcode,t.duration, t.realdate as time,t.aditionaldata,o "
                + " from TgeneTransactionLog t ,TbpmProcessInstance o"
                + " where t.pk in (select i.pk from TbpmProcessInstance i where coalesce(i.finalized, 'N')='Y')  and t.pk = o.pk ");
        String creation = "" + qr.get("creationdate");
        creation = (creation.compareTo("") == 0) ? null : creation;
        String enddate = "" + qr.get("enddate");
        enddate = (enddate.compareTo("") == 0) ? null : enddate;
        if ((creation != null) && (enddate != null)) {
            jpql.append(" and o.creationdate>=:creationdate ");
            jpql.append(" and o.enddate<=:enddate ");
        }
        return this.manageParameters(qr, jpql, creation, enddate);
    }

    /**
     * Manage parameters.
     * 
     * @param qr the qr
     * @param jpql the jpql
     * @param creation the creation
     * @param enddate the enddate
     * @return query
     * @throws Exception la exception
     */
    private Query manageParameters(QueryRequest qr, StringBuilder jpql, String creation, String enddate) throws Exception {
        
    	//Verifica consulta frontend jsf/dojo
    	Query qry = this.processQuery(qr, jpql);
    	
        if ((creation != null) && (enddate != null)) {
            qry.setParameter("creationdate", (Date)qr.get("creationdate"));
            APPDates ad = new APPDates((Date) qr.get("enddate"));
            ad.addField(Calendar.DAY_OF_YEAR, 1);
            qry.setParameter("enddate", ad.getDate());
        }
        return qry;
    }

    /**
     * Metodo que maneja la peticion del frontend jsf/dojo
     * @param qr
     * @param jpql
     * @return
     * @throws Exception
     */
    private Query processQuery(QueryRequest qr, StringBuilder jpql) throws Exception{
    	Query qry = null;
    	if(qr.isJsf()){
    		DtoQuery dto = (DtoQuery)qr.getQueryTables().get("TRANSACTIONLOG");
    		GeneralQuery.addParametersJSF(jpql, dto);
    		qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
    		GeneralQuery.setParametersJSF(jpql, dto, qry);
    	}else{
    		QueryBean qb = (QueryBean) qr.get("TRANSACTIONLOG");
            Map<String, Object> criteria = new HashMap<String, Object>();
            GeneralQuery.addParameters(qb, jpql, criteria);
            jpql.append(",creationdate");
            qry = PersistenceHelper.getEntityManager().createQuery(jpql.toString());
            GeneralQuery.setParameters(qb, criteria, qry);
    	}
    	return qry;
    }
    /** Sentencia que consulta el nombre del usuario. */
    public static final String SQL = "select a.name from TcustPersonDetail a ,TsafeUser b" + " where a.pk.personcode = b.personcode"
            + " and b.pk=:usercode" + " and a.pk.dateto=:dateto";
}
