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

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.context.RequestContext;

import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.query.Filter;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.enums.EnumLovOption;
import com.fp.frontend.helper.CallerHelper;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;

/**
 * Clase controladora del lov asociado al bean TgeneCatalog.
 *
 * @author Jorge Vaca.
 * @version 2.1
 */
@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class TransactionLovController extends AbstractController<TgeneTransaction> {

    private String moduleCode = null;

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

    @PostConstruct
    private void postconstruct() {
        this.init();
        try {
            this.moduleCode = CallerHelper.getLovParameter("moduleCode");
        } catch (Exception e) {
            // TODO: handle exception
        }
        // 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 = "TRANSACTIONLOV";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            if ((this.moduleCode == null) || this.moduleCode.isEmpty()) {
                if (!super.existAtLeastOneFilterValue()) {
                    MessageHelper.setMessageError("msg_filterrequird");
                    return;
                }
            }

            Request request = this.callerhelper.getRequest();
            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.pk.transactionmodule, t.pk.transactioncode, t.pk.transactionversion");

            if ((this.moduleCode != null) && !this.moduleCode.isEmpty()) {
                Filter f = null;
                if ((super.getMfilters().get("pk.transactionmodule") != null) && !super.getMfilters().get("pk.transactionmodule").equals("")) {
                    f = new Filter();
                    f.setSql("t.pk.transactionmodule = '" + this.moduleCode + "'");
                } else {
                    f = new Filter("pk.transactionmodule", "=" + this.moduleCode);
                }
                dto.addFiltro(f);
            }

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

    public void settransaction() {
        // se utiliza en la pagina del lov.
        RequestContext.getCurrentInstance().closeDialog(this.record);
    }

    public void settransaction(TgeneTransaction tgeneTransaction) {
        // se utiliza en la pagina del lov.
        RequestContext.getCurrentInstance().closeDialog(tgeneTransaction);
    }

    public static void openLov(Map<String, List<String>> params) {
        Map<String, Object> options = new HashMap<String, Object>();
        // hint: ver EnumLovOption para las opciones del modal
        options.put(EnumLovOption.MODAL.getLabel(), true);
        options.put(EnumLovOption.HEIGHT.getLabel(), 400);
        options.put(EnumLovOption.WIDTH.getLabel(), 700);
        options.put(EnumLovOption.RESIZABLE.getLabel(), false);

        // lovpersona es el nombre de la pagina
        RequestContext.getCurrentInstance().openDialog("/pages/general/lov/transactionLov.xhtml", options, params);
    }

    public String getModuleCode() {
        return this.moduleCode;
    }

    public void setModuleCode(String moduleCode) {
        this.moduleCode = moduleCode;
    }
}
