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.pgeneral.lov.ProcessLovControler;
import com.fp.frontend.controller.pgeneral.lov.TransactionLovController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.proc.TgeneProcess;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;
import com.fp.persistence.pgeneral.trans.report.TgeneTransactionReports;

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

    private static final long serialVersionUID = 1L;

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

    /**
     * Crea una instancia de TgeneTransactionReports 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("REPORT");
    }

    /**
     * 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", "REPORT");
            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);

            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<TgeneTransactionReports>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneTransactionReports>) 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);
    }

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

    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<>();
        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("processdesc", t.getShortdesc());
    }

}
