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

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pbpm.gene.TbpmTaskComments;
import com.fp.persistence.pgeneral.log.TgeneTransactionLog;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;
import com.fp.persistence.pgeneral.trans.TgeneTransactionKey;

// TODO: Auto-generated Javadoc
/**
 * Class EndedFlowDetail encargada de.
 * 
 * @author gfiallos
 */
public class EndedFlowDetail extends QueryRule {

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

    /** Constante SQL. */
    private static final String SQL = "SELECT "
            + "    a.activityname,a.sequence,a.usercode,a.groupcode,a.created,a.completed,a.expectedtime,a.response ,a.module,a.transaction,a.version, ( "
            + "      SELECT " + "          z.name " + "        FROM " + "          tgenetransaction z " + "        WHERE "
            + "          z.transactionmodule=a.module " + "          AND z.transactioncode=a.transaction "
            + "          AND z.transactionversion=a.version),a.taskid " + "  FROM " + "    tbpmactivities a " + "  WHERE "
            + "    a.journalid=:journal " + "  ORDER BY " + "    created";

    /** El valor de id. */
    private String id;

    /** El valor de resp. */
    private Response resp;

    /** El valor de sdf1. */
    private SimpleDateFormat sdf1;

    /**
     * Process.
     * 
     * @param pQueryRequest the query request
     * @return query request
     * @throws Exception la exception
     */
    @Override
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        this.sdf1 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        this.id = pQueryRequest.getString("ID");
        this.resp = pQueryRequest.getResponse();
        TgeneTransactionLog tl = TgeneTransactionLog.find(PersistenceHelper.getEntityManager(), this.id);
        this.resp.put("DATA", tl.getAditionaldata());
        TgeneTransaction t = TgeneTransaction.find(PersistenceHelper.getEntityManager(),
                new TgeneTransactionKey(tl.getTransactionmodule(), tl.getTransactioncode(), tl.getTransactionversion()));
        this.resp.put("TRN", t.getName());
        this.manageActivities();
        return pQueryRequest;
    }

    /**
     * Manage activities.
     * 
     * @throws Exception la exception
     */
    public void manageActivities() throws Exception {
        Query q = PersistenceHelper.createNativeQuery(EndedFlowDetail.SQL);
        q.setParameter("journal", this.id);
        @SuppressWarnings("unchecked")
        List<Object> l = q.getResultList();
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

        DecimalFormat df = new DecimalFormat("00");
        for (Object obj : l) {
            Map<String, Object> rec = new HashMap<String, Object>();
            Object[] oData = (Object[]) obj;
            rec.put("activityname", oData[0] + " (" + oData[11] + ")");
            rec.put("sequence", oData[1]);
            rec.put("usercode", oData[2]);
            rec.put("groupcode", oData[3]);
            Timestamp completed = ((Timestamp) oData[5]);
            Timestamp created = ((Timestamp) oData[4]);
            rec.put("created", this.sdf1.format(created));
            rec.put("completed", this.sdf1.format(completed));
            Long exp = Long.valueOf("" + oData[6]) / 1000;
            BigDecimal aux = new BigDecimal(exp / 60);
            rec.put("expectedtime", df.format(aux.intValue()) + ":" + df.format(exp % 60));
            Long real = Long.valueOf("" + (completed.getTime() - created.getTime())) / 1000;
            aux = new BigDecimal(real / 60);
            rec.put("realtime", df.format(aux.intValue()) + ":" + df.format(real % 60));
            rec.put("response", oData[7]);
            rec.put("obs", this.getComments(Long.valueOf("" + oData[12])));
            data.add(rec);
        }
        this.resp.put("TBPMACTIVITIES", data);
    }

    /**
     * Obtiene el valor de comments.
     * 
     * @param pTID the tID
     * @return Valor de comments
     * @throws Exception la exception
     */
    private String getComments(long pTID) throws Exception {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            String jpql = "from TbpmTaskComments tc where tc.taskid=:tid";
            Query q = PersistenceHelper.createQuery(jpql);
            q.setParameter("tid", pTID);
            @SuppressWarnings("unchecked")
            List<TbpmTaskComments> tc = q.getResultList();
            for (TbpmTaskComments tbpmTaskComments : tc) {
                pw.println(tbpmTaskComments.getUsercode() + " : " + this.sdf1.format(tbpmTaskComments.getAdded()));
                pw.println(tbpmTaskComments.getText());
            }
        } finally {
            pw.close();
        }
        return sw.toString();
    }
}
