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

import java.util.List;
import java.util.Map;

import com.fp.base.persistence.util.helper.GeneralDescriptions;
import com.fp.bpmlib.BPMException;
import com.fp.bpmlib.ProcessUtil;
import com.fp.bpmlib.db.DataHelper;
import com.fp.bpmlib.flow.Monitor;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pbpm.gene.TbpmProcessInstance;
import com.fp.persistence.pgeneral.log.TgeneTransactionLog;


/**
 * Class FlowMonitor encargada de.
 * 
 * @author gfiallos
 */
public class FlowMonitor extends QueryRule {

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

    /** El valor de pid. */
    private Long pid;

    /** El valor de request. */
    private QueryRequest request;

    /**
     * Process.
     * 
     * @param pQueryRequest the query request
     * @return query request
     * @throws Exception la exception
     */
    @Override
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        this.request = pQueryRequest;
        this.pid = this.request.getLong("PID");
        if (this.pid == null) {
            throw new BPMException("BPM-0004", "LA INSTANCIA {0} NO ESTA DISPONIBLE O YA FUE FINALIZADA", this.pid);
        }
        this.manageFlow();
        this.manageOrigin();
        return pQueryRequest;
    }

    /**
     * Manage flow.
     * 
     * @throws Exception la exception
     */
    protected void manageFlow() throws Exception {
        Monitor monitor = new Monitor(this.pid);
        //p.setVariable("TEST", FormatDates.getInstance().getDataBaseTimestamp());
        this.request.getResponse().put("status", monitor.getStatus());
        Object tasks = ProcessUtil.getFirstDoneTaskMetaData(monitor);
        this.request.getResponse().put("FIRST", tasks);
    }

    /**
     * Manage origin.
     * 
     * @throws Exception la exception
     */
    protected void manageOrigin() throws Exception {
        TbpmProcessInstance pro = DataHelper.getInstance().getTbpmProcessInstance(this.pid);
        TgeneTransactionLog log = TgeneTransactionLog.find(PersistenceHelper.getEntityManager(), pro.getPk());
        List<Map<String, Object>> data = ProcessUtil.getInstance().transactionData(pro.getPk(), this.request);
        this.request.getResponse().put("origin", data);
        this.request.getResponse().put(
                "TRN",
                log.getTransactionmodule() + "-" + log.getTransactioncode() + "-" + log.getTransactionversion() + " "
                        + GeneralDescriptions.getTransactiondesc(log.getTransactionmodule(), log.getTransactioncode(), log.getTransactionversion()));
    }



}
