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

import java.math.BigDecimal;
import java.util.ArrayList;

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.frontend.controller.AbstractController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.menu.TgeneMenuLevel;

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

    private static final long serialVersionUID = 1L;

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

    @Override
    protected void querydatabase() {
        MessageHelper.setMessageError("msg_notQuery");
    }

    @Override
    public void save() {
        MessageHelper.setMessageError("msg_notSave");
    }

    /**
     * Obtiene el codigo del levelcode
     */
    public Integer getLevelCode(Integer menucode) {
        Integer levelcode = null;
        try {
            Request request = this.callerhelper.getRequest();
            request.put("queryalias", "EXECUTESQL");
            request.put("querytype", "P");
            request.put("isUniqueResult", "Y");
            request.put("sql", "select coalesce(max(LEVELCODE), 0)+1 from TGENEMENULEVEL where MENUCODE = " + menucode);

            Response resp = this.callerhelper.executeQuery(request);

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                levelcode = null;
                MessageHelper.setMessageError(resp);
            } else {
                levelcode = ((BigDecimal) resp.get("result")).intValue();
            }

        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
        return levelcode;
    }
}
