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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.kie.api.task.model.Content;
import org.kie.api.task.model.Task;

import com.fp.base.persistence.util.helper.GeneralDescriptions;
import com.fp.bpmlib.task.client.HumanTaskClient;
import com.fp.bpmlib.task.client.TaskUtil;
import com.fp.common.helper.Constant;
import com.fp.dto.data.TransactionDTO;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.dto.save.SaveRequest;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;
import com.fp.persistence.pgeneral.trans.TgeneTransactionKey;

// TODO: Auto-generated Javadoc
/**
 * Class TransactionList encargada de listar las transacciones para el buzón de la persona.
 * 
 * @author gfiallos
 */
public class TransactionList extends QueryRule {

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

    /** El valor de htc. */
    private HumanTaskClient htc = null;

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

    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

    /** El valor de trn. */
    private final Map<String, Integer> trn = new HashMap<String, Integer>();

    Map<String, Object> mtransaux = new HashMap<String, Object>();

    /**
     * Process.
     * 
     * @param pQueryRequest the query request
     * @return query request
     * @throws Exception la exception
     */
    @SuppressWarnings("unchecked")
    @Override
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        htc = new HumanTaskClient();
        try {
            request = pQueryRequest;
            if(request.get("codeS")==null)
            {
                this.addTransactionList(pQueryRequest.getLanguage());
            }
            else
            {
                this.addTransactionList(pQueryRequest.getLanguage(),request.get("codeS").toString());
            }

            Set<String> s = mtransaux.keySet();
            for (String key : s) {
                data.add((Map<String, Object>) mtransaux.get(key));
            }
            pQueryRequest.getResponse().put("transactions", data);
            return pQueryRequest;
        } finally {
            htc.close();
        }
    }
    
    
    
    /**
     * METODO PARA OBTENER EL TIPO DE AUTORIZACION CON LOGSOLICITUDE
     */
   
    
    /**
     * Prepara la lista de Tareas.
     * 
     * @throws Exception la exception
     */
    @SuppressWarnings("unchecked")
    private void addTransactionList(String language) throws Exception {
        List<Object[]> t = htc.getUnfinishedTasksByUser(request.getUser());
        Task task = null;
        TaskUtil tu = null;
        TransactionDTO tr = null;
        Integer count = null;
        Map<String, Object> mtran = null;
        for (Object[] obj : t) {
            task = (Task) obj[0];
            tu = new TaskUtil(task, htc);

            tr= tu.getTransaction();
            count = trn.get(tr.toString());
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            trn.put(tr.toString(), count);

            mtran = (Map<String, Object>) mtransaux.get(tr.toString());
            if (mtran == null) {
                mtran = this.addTransactionData(tu);
                mtransaux.put(tr.toString(), mtran);
            }
            mtran.put("c", count);

            // Adiciona datos de una tarea.
            TransactionTasks.addTask(mtran, tu, language);
        }
    }

    @SuppressWarnings({ "unchecked", "unused", "rawtypes" })
    private void addTransactionList(String language, String codSolicitud) throws Exception {
        List<Object[]> t = htc.getUnfinishedTasksByUser(request.getUser());
        Task task ;
        Content c;
        TaskUtil tu;
        TransactionDTO tr ;
        String codS ;
        Integer count;
        Map<String, Object> mtran;
        for (Object[] obj : t) {
            task = (Task) obj[0];
            c = (Content) obj[1];
            tu = new TaskUtil(task, htc);

            ((SaveRequest)(((Map)tu.getActualData().get("maia")).get("request"))).get("csolicitud");
            tr = tu.getTransaction();
            if(tu.getActualData().get("maia") instanceof Map<?, ?>)
            {
                if(((Map)tu.getActualData().get("maia")).get("request") != null)
                {
                    if((((Map)tu.getActualData().get("maia")).get("request")) instanceof SaveRequest)
                    {
                        Object csolicitud = ((SaveRequest)(((Map)tu.getActualData().get("maia")).get("request"))).get("csolicitud");
                        if(csolicitud!=null){
                            codS = csolicitud.toString();
                            if(!codS.equals(codSolicitud))
                            {
                                continue;
                            }
                        }
                    }
                }
            }

            count = trn.get(tr.toString());
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            trn.put(tr.toString(), count);

            mtran = (Map<String, Object>) mtransaux.get(tr.toString());
            if (mtran == null) {
                mtran = this.addTransactionData(tu);
                mtransaux.put(tr.toString(), mtran);
            }
            mtran.put("c", count);

            // Adiciona datos de una tarea.
            TransactionTasks.addTask(mtran, tu, language);
        }
    }
    

    private Map<String, Object> addTransactionData(TaskUtil tu) throws Exception {
        Map<String, Object> rec = new HashMap<String, Object>();
        TransactionDTO tr = tu.getTransaction();
        rec.put("m", tr.getModule());
        rec.put("t", tr.getTransaction());
        rec.put("v", tr.getVersion());
        rec.put("n", Constant.capitalize(GeneralDescriptions.getTransactiondesc(tr.getModule(), tr.getTransaction(), tr.getVersion())));
        TgeneTransactionKey k = new TgeneTransactionKey(tr.getModule(), tr.getTransaction(), tr.getVersion());
        TgeneTransaction t = TgeneTransaction.find(PersistenceHelper.getEntityManager(), k);
        rec.put("p", t.getPage());
        rec.put("name", t.getName());
        rec.put("pjsf", t.getJsfpage());
        rec.put("pjsfurl", t.getJsfpage() + "?m=" + tr.getModule() + "&t=" + tr.getTransaction() + "&v=" + tr.getVersion());
        rec.put("q", t.getAutoquery());
        rec.put("f", t.getSignature());
        return rec;
    }
}