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.MessageTemplatesLovController;
import com.fp.frontend.controller.pgeneral.message.MessageTemplatesController;
import com.fp.frontend.controller.pgeneral.product.ModuleController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.message.TgeneMessageTemplates;
import com.fp.persistence.pgeneral.product.TgeneModule;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;

/**
 * Clase controladora del bean TgeneTransaction.
 *
 * @author Andres E. Carpio
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class TransactionController extends AbstractController<TgeneTransaction> {

    private static final long serialVersionUID = 1L;
    List<TgeneModule> lmodule;
    List<TgeneMessageTemplates> lmessage;

    public TransactionController() throws Exception {
        super(TgeneTransaction.class);
    }

    @PostConstruct
    private void postconstruct() {
        this.init();
        this.lmodule = ModuleController.find();
        this.lmessage = MessageTemplatesController.find();

        // 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 = "TRANSACTION";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            Request request = this.callerhelper.getRequest();
            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.pk.transactionmodule, t.pk.transactioncode, t.pk.transactionversion, name");

            // subqueries
            SubQuery subquery = new SubQuery("TgeneMessageTemplates", "description", "messagedesc",
                    "i.pk = t.messagecode");
            dto.addSubQuery(subquery);

            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<TgeneTransaction>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneTransaction>) 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();
            if (!dtosave.pendingProcess()) {
                return;
            }
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
            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);
        }
    }

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

    public void onReturnMessageTemplateLov(SelectEvent event) throws Exception {
        TgeneMessageTemplates t = (TgeneMessageTemplates) event.getObject();
        this.record.setMessagecode(t.getPk());
        this.record.put("messagedesc", t.getDescription());
    }

    public void removemessage() throws Exception {
        if (record != null) {
            record.setMessagecode(null);
            record.modifiedData.put("messagedesc", null);
        }
    }

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

    /**
     * Entrega el valor de: lmodule
     *
     * @return List<TgeneModule>
     */
    public List<TgeneModule> getLmodule() {
        return this.lmodule;
    }

    /**
     * Fija el valor de: lmodule
     *
     * @param lmodule Valor a fijar en el atributo.
     */
    public void setLmodule(List<TgeneModule> lmodule) {
        this.lmodule = lmodule;
    }

    /**
     * Entrega el valor de: lmessage
     *
     * @return List<TgeneMessageTemplates>
     */
    public List<TgeneMessageTemplates> getLmessage() {
        return this.lmessage;
    }

    /**
     * Fija el valor de: lmessage
     *
     * @param lmessage Valor a fijar en el atributo.
     */
    public void setLmessage(List<TgeneMessageTemplates> lmessage) {
        this.lmessage = lmessage;
    }

}
