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.ManagedProperty;
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;

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

    private static final long serialVersionUID = 1L;

    public LevelDescController() throws Exception {
        super(TgeneMenuLevelDesc.class);
    }

    @ManagedProperty(value = "#{levelController}")
    private LevelController level;

    /**
     * Atributo para el objeto TgeneMenu
     */
    private TgeneMenu genemenu;
    /**
     * Atributo para el codigo levelcode
     */
    private Integer levelcode;

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

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

    @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.languagecode", this.getLoginController().getRequest().getLanguage());

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

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

            // subqueries 1
            SubQuery subquery = new SubQuery("TgeneMenuLevel", "presentationorder", "presentationorder",
                    "i.pk.menucode = t.pk.menucode and i.pk.levelcode = t.pk.levelcode");
            dto.addSubQuery(subquery);

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

            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<TgeneMenuLevelDesc>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneMenuLevelDesc>) 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 (super.getMfilters().get("pk.menucode") == null) {
            MessageHelper.setMessageError("msg_menucodeRequired");
            return;
        }
        super.create();
        this.record.put("menudesc", this.genemenu.getDescription());
        this.record.getPk().setMenucode(this.genemenu.getPk());
        this.record.getPk().setLevelcode(this.levelcode++);
        this.record.getPk().setLanguagecode(this.getLoginController().getRequest().getLanguage());
    }

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

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

    /**
     * Entrega el valor de level
     *
     * @return level
     */
    public LevelController getLevel() {
        return level;
    }

    /**
     * Fija el valor de level
     *
     * @param level
     */
    public void setLevel(LevelController level) {
        this.level = level;
    }

}
