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

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

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

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.helper.MessageHelper;
import com.fp.persistence.pgeneral.menu.TgeneMenu;
import com.fp.persistence.pgeneral.menu.TgeneMenuLevelDesc;
import com.fp.persistence.pgeneral.menu.TgeneMenuLevelTran;

/**
 * Clase controladora del bean TgeneMenuLevelTran.
 *
 * @author WPA
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class MenuLevelTranController extends AbstractController<TgeneMenuLevelTran> {

    private static final long serialVersionUID = 1L;

    public MenuLevelTranController() throws Exception {
        super(TgeneMenuLevelTran.class);
    }

    /**
     * Atributo para el objeto TgeneMenu
     */
    private TgeneMenu genemenu;

    /**
     * Atributo para el objeto TgeneMenu
     */
    private TgeneMenuLevelDesc genemenulevel;

    @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.genemenu = null;
            this.genemenulevel = null;
            this.recperpage = 10; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "TGENEMENULEVELTRAN";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Inicializa las paginas en la consulta
     */
    public void initRecPage() {
        this.page = 0;
        this.recperpage = 10;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            //Filtros
            this.getMfilters().put("pk.menucode", this.genemenu != null ? this.genemenu.getPk().toString() : null);
            this.getMfilters().put("pk.levelcode", this.genemenulevel != null ? this.genemenulevel.getPk().getLevelcode().toString() : null);

            if (super.getMfilters().get("pk.menucode") == null) {
                MessageHelper.setMessageError("msg_menucodeRequired");
                return;
            }
            if (super.getMfilters().get("pk.levelcode") == null) {
                MessageHelper.setMessageError("msg_menuLevelRequired");
                return;
            }

            Request request = this.callerhelper.getRequest();
            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.presentationorder"); // En en string van todos los campos de

            // subqueries
            SubQuery subquery = new SubQuery("TgeneTransaction", "name", "name",
                    "i.pk.transactionmodule = t.pk.transactionmodule and "
                    + "i.pk.transactioncode = t.pk.transactioncode and "
                    + "i.pk.transactionversion = t.pk.transactionversion");
            dto.addSubQuery(subquery);

            // subqueries 1
            SubQuery subquery1 = new SubQuery("TgeneMenuLevelDesc", "description", "leveldescription",
                    "i.pk.menucode = t.pk.menucode and i.pk.levelcode = t.pk.levelcode and i.pk.languagecode = '" + this.getLoginController().getRequest().getLanguage() + "'");
            dto.addSubQuery(subquery1);

            // subqueries 2
            SubQuery subquery2 = new SubQuery("TgeneMenu", "description", "menudesc",
                    "i.pk = t.pk.menucode");
            dto.addSubQuery(subquery2);

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

    /**
     * Crea una instancia de TgeneTransactionProcess y marca el registro como
     * nuevo.
     *
     * @throws Exception
     */
    @Override
    public void create() throws Exception {
        if (this.genemenu == null) {
            MessageHelper.setMessageError("msg_menucodeRequired");
            return;
        }
        if (this.genemenulevel == null) {
            MessageHelper.setMessageError("msg_menuLevelRequired");
            return;
        }
        super.create();
        System.out.println("REGISTRO " + this.record);
        this.record.put("menudesc", this.genemenu.getDescription());
        this.record.put("leveldescription", this.genemenulevel.getDescription());
        this.record.getPk().setMenucode(this.genemenulevel.getPk().getMenucode());
        this.record.getPk().setLevelcode(this.genemenulevel.getPk().getLevelcode());
    }

    /**
     * Entrega el objeto TgeneMenuLevelDesc
     *
     * @return genemenulevel
     */
    public TgeneMenuLevelDesc getGenemenulevel() {
        return genemenulevel;
    }

    /**
     * Fija el objeto TgeneMenuLevelDesc
     *
     * @param genemenulevel
     */
    public void setGenemenulevel(TgeneMenuLevelDesc genemenulevel) {
        this.genemenulevel = genemenulevel;
    }

    /**
     * Entrega el objeto TgeneMenu
     *
     * @return genemenu
     */
    public TgeneMenu getGenemenu() {
        return genemenu;
    }

    /**
     * Entrega el objeto TgeneMenu
     *
     * @return genemenu
     */
    public void setGenemenu(TgeneMenu genemenu) {
        this.genemenu = genemenu;
    }
}
