package com.fp.frontend.controller.pgeneral.trans;

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.event.SelectEvent;

import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.query.SubQuery;
import com.fp.dto.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.pbpm.lov.TbpmRulesLovController;
import com.fp.frontend.controller.pgeneral.lov.MessageTemplatesLovController;
import com.fp.frontend.controller.pgeneral.lov.ProcessLovControler;
import com.fp.frontend.controller.pgeneral.lov.TransactionLovController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pbpm.gene.TbpmRules;
import com.fp.persistence.pgeneral.message.TgeneMessageTemplates;
import com.fp.persistence.pgeneral.proc.TgeneProcess;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;
import com.fp.persistence.pgeneral.trans.TgeneTransactionProcess;

/**
 * Clase controladora del bean TgeneTransactionProcess.
 *
 * @author Jorge Vaca.
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class TransactionProcessController extends AbstractController<TgeneTransactionProcess> {

    private static final long serialVersionUID = 1L;

    public TransactionProcessController() throws Exception {
        super(TgeneTransactionProcess.class);
    }

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();

    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza
     * el controlador.
     */
    private void init() {
        try {
            this.recperpage = 10; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "CATALOG";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Crea una instancia de TgeneTransactionProcess y marca el registro como
     * nuevo.
     *
     * @throws Exception
     */
    @Override
    public void create() throws Exception {
        if (super.getMfilters().get("pk.transactionmodule") == null) {
            MessageHelper.setMessageError("msg_transactionrequird");
            return;
        }
        super.create();
        this.record.getPk().setTransactionmodule(super.getMfilters().get("pk.transactionmodule"));
        this.record.getPk().setTransactioncode(Integer.valueOf(super.getMfilters().get("pk.transactioncode")));
        this.record.getPk().setTransactionversion(Integer.valueOf(super.getMfilters().get("pk.transactionversion")));
        this.record.setCatalogcodetypeprocess("PROCESSTYPE");
        this.record.setCatalogtypeprocess("TRANSACTION");
    }

    /**
     * Actualiza datos de registros nuevos o modifiados, si el registro es nuevo
     * se adiciona a lista de nuevos, si es actualizado se adiciona a la lista
     * de actualizados.
     *
     * @throws Exception
     */
    @Override
    public void update() throws Exception {
        if (record.getProcesscode() == null) {
            MessageHelper.setMessageError("msg_processrequired");
            return;
        }
        super.update();
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            super.addFilter("catalogtypeprocess", "TRANSACTION");
            if (super.getMfilters().get("pk.transactioncode") == null) {
                MessageHelper.setMessageError("msg_catalogrequird");
                return;
            }
            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.executionorder");

            // subqueries
            SubQuery subquery = new SubQuery("TgeneProcess", "shortdesc", "nprocess",
                    "i.pk.processcode = t.processcode and i.pk.catalogtypeprocess = t.catalogtypeprocess");
            dto.addSubQuery(subquery);

            // subqueries 1
            SubQuery subquery1 = new SubQuery("TgeneMessageTemplates", "description", "messagedesc",
                    "i.pk  = cast(t.flowmessagecode as int)");
            dto.addSubQuery(subquery1);

            // subqueries 2		
            SubQuery subquery2 = new SubQuery("TbpmRules", "description", "flowdesc",
                    "i.pk.rulecode = t.processname and i.pk.companycode = " + super.getLoginController().getRequest().getCompany().toString());
            dto.addSubQuery(subquery2);

            // subqueries 3
            SubQuery subquery3 = new SubQuery("TgeneProcess", "shortdesc", "processdesc",
                    "i.pk.processcode = t.processcode and i.pk.catalogtypeprocess=t.catalogtypeprocess and i.pk.catalogcodetypeprocess=t.catalogcodetypeprocess");
            dto.addSubQuery(subquery3);

            // subqueries 3
            SubQuery subquery4 = new SubQuery("TbpmRules", "description", "ruledesc",
                    "i.pk.rulecode = t.rulename and i.pk.companycode = " + super.getLoginController().getRequest().getCompany().toString());
            dto.addSubQuery(subquery4);

            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(this.beanalias, dto); // permite adicionar mas de una tabla.

            Request request = this.callerhelper.getRequest();
            request.setQueryTables(mtables);

            Response resp = this.callerhelper.executeQuery(request);

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.lrecord = new ArrayList<TgeneTransactionProcess>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneTransactionProcess>) resp.get(this.beanalias);
                super.postQuery(this.lrecord);
            }

        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void save() {
        try {
            DtoSave dtosave = super.getDtoSave();
            dtosave.setReturnpk(true); // Para que el core devuelva el pk de los registros nuevos.
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();

            Request request = this.callerhelper.getRequest();
            msave.put(this.beanalias, dtosave); // adicionar metadata de mantenimiento para cada tabla.

            request.setSaveTables(msave);
            Response resp = this.callerhelper.executeSave(request);
            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {
                this.postCommit(resp);
                MessageHelper.setMessageInfo(resp);
            } else {
                MessageHelper.setMessageError(resp);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void postCommit(Response response) throws Exception {
        super.postCommitGeneric(response, this.beanalias);
    }

    /**
     * Abre el lov de transacciones
     */
    public void openTransactionLov() {
        Map<String, List<String>> params = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("TRANSACTION"); // valor del parametro
        params.put("processtype", l);

        TransactionLovController.openLov(params);
    }

    /**
     * Gestiona la respuesta del lov de transacciones
     *
     * @param event
     * @throws Exception
     */
    public void onReturnTransactionLov(SelectEvent event) throws Exception {
        TgeneTransaction t = (TgeneTransaction) event.getObject();
        super.addFilter("pk.transactionmodule", t.getPk().getTransactionmodule());
        super.addFilter("pk.transactioncode", t.getPk().getTransactioncode().toString());
        super.addFilter("pk.transactionversion", t.getPk().getTransactionversion().toString());
        super.addField("transactionname", t.getName());
        this.query();
    }

    /**
     * Abre el lov de comandos
     */
    public void openProcessLov() {
        Map<String, List<String>> params = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("TRANSACTION"); // valor del parametro
        params.put("processtype", l);
        ProcessLovControler.openLov(params);
    }

    /**
     * Gestiona la respuesta del lov de comandos
     *
     * @param event
     * @throws Exception
     */
    public void onReturnPrcoessLov(SelectEvent event) throws Exception {
        TgeneProcess t = (TgeneProcess) event.getObject();
        this.record.setProcesscode(t.getPk().getProcesscode());
        this.record.put("nprocess", t.getShortdesc());
    }

    /**
     * Llama al Lov de Mensajes
     */
    public void openMessageTemplateLov() {
        Map<String, List<String>> params = new HashMap<>();
        MessageTemplatesLovController.openLov(params);
    }

    /**
     * Gestiona la respuesta del Lov de Mensajes
     *
     * @param event
     * @throws Exception
     */
    public void onReturnMessageTemplateLov(SelectEvent event) throws Exception {
        TgeneMessageTemplates t = (TgeneMessageTemplates) event.getObject();
        this.record.setFlowmessagecode(t.getPk().toString());
        this.record.put("messagedesc", t.getDescription());
    }

    /**
     * Elimina el codigo de mensaje
     *
     * @throws Exception
     */
    public void removemessage() throws Exception {
        if (record != null) {
            record.setFlowmessagecode(null);
            record.modifiedData.put("messagedesc", null);
        }
    }

    /**
     * Llama al Lov de Mensajes
     */
    public void openFlowLov() {
        Map<String, List<String>> params = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("F"); // valor del parametro
        params.put("filetype", l);
        TbpmRulesLovController.openLov(params);
    }

    /**
     * Gestiona la respuesta del Lov de Mensajes
     *
     * @param event
     * @throws Exception
     */
    public void onReturnFlowLov(SelectEvent event) throws Exception {
        TbpmRules t = (TbpmRules) event.getObject();
        this.record.setProcessname(t.getPk().getRulecode());
        //this.record.setPackagename(t.getPackagename());
        this.record.put("flowdesc", t.getDescription());
    }

    /**
     * Elimina el codigo de mensaje
     *
     * @throws Exception
     */
    public void removeflow() throws Exception {
        if (record != null) {
            record.setProcessname(null);
            record.modifiedData.put("flowdesc", null);
        }
    }

    /**
     * Llama al Lov de Mensajes
     */
    public void openRuleLov() {
        Map<String, List<String>> params = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("R"); // valor del parametro
        params.put("filetype", l);
        TbpmRulesLovController.openLov(params);
    }

    /**
     * Gestiona la respuesta del Lov de Mensajes
     *
     * @param event
     * @throws Exception
     */
    public void onReturnRuleLov(SelectEvent event) throws Exception {
        TbpmRules t = (TbpmRules) event.getObject();
        this.record.setRulename(t.getPk().getRulecode());
        this.record.put("ruledesc", t.getDescription());
    }

    /**
     * Elimina el codigo de mensaje
     *
     * @throws Exception
     */
    public void removerule() throws Exception {
        if (record != null) {
            record.setRulename(null);
            record.modifiedData.put("ruledesc", null);
        }
    }
}
