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

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.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.gene.TgeneTransactionQuery;
import com.fp.persistence.pgeneral.proc.TgeneProcess;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;

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

    private static final long serialVersionUID = 1L;

    public TransactionQueryController() throws Exception {
        super(TgeneTransactionQuery.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 = "TRANSACTIONPROCESS";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * 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 (this.record.getProcesscode() == null) {
            MessageHelper.setMessageError("msg_processrequired");
            return;
        }
        super.update();
    }

    public void openTransactionLov() {
        Map<String, List<String>> params = new HashMap<>();
        TransactionLovController.openLov(params);
    }

    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("name", t.getName());
        this.query();
    }

    /**
     * Crea una instancia de TgeneTransactionQuery 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.setCatalogtypeprocess("QUERY");
        this.record.setCatalogcodetypeprocess("PROCESSTYPE");
    }

    public DtoQuery getDtoQuery() throws Exception {
        DtoQuery dto = super.getDtoQuery(true);
        dto.setOrderby("t.executionorder");
        // subqueries
        SubQuery subquery = new SubQuery("TgeneProcess", "shortdesc", "shortdesc", "i.pk.processcode = t.processcode");
        dto.addSubQuery(subquery);
        return dto;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        if (super.getMfilters().get("pk.transactionmodule") == null) {
            MessageHelper.setMessageError("msg_filterrequird");
            return;
        }
        try {
            Request request = this.callerhelper.getRequest();
            DtoQuery dto = this.getDtoQuery();
            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(this.beanalias, dto); // permite adicionar mas de una tabla.
            request.setQueryTables(mtables);
            Response resp = this.callerhelper.executeQuery(request);
            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.lrecord = new ArrayList<TgeneTransactionQuery>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneTransactionQuery>) resp.get(this.beanalias);
                super.postQuery(this.lrecord);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void save() {
        try {
            Request request = this.callerhelper.getRequest();
            DtoSave dtosave = super.getDtoSave();
            dtosave.setReturnpk(true); // Para que el core devuelva el pk de los
            // registros nuevos.
            if (!dtosave.pendingProcess()) {
                return;
            }
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
            msave.put(this.beanalias, dtosave);
            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);
    }

    public void openProcessLov() {
        Map<String, List<String>> params = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("QUERY"); // valor del parametro
        params.put("processtype", l);
        ProcessLovControler.openLov(params);
    }

    public void onReturnProcessLov(SelectEvent event) throws Exception {
        TgeneProcess t = (TgeneProcess) event.getObject();
        this.record.setProcesscode(t.getPk().getProcesscode());
        this.record.put("shortdesc", t.getShortdesc());
    }

    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);
    }

    public void onReturnRuleLov(SelectEvent event) throws Exception {
        TbpmRules t = (TbpmRules) event.getObject();
        // this.record.setProcesscode(t.getPk().getRulecode());
        this.record.setRulename(t.getPk().getRulecode());
        this.record.put("ruledesc", t.getDescription());
    }

    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);
    }

    public void onReturnFlowLov(SelectEvent event) throws Exception {
        TbpmRules t = (TbpmRules) event.getObject();
        this.record.setProcessname(t.getPk().getRulecode());
        this.record.put("flowdesc", t.getDescription());
    }
}
