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

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

    private static final long serialVersionUID = 1L;

    public SubLevelController() throws Exception {
        super(TgeneMenuSubLevel.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 = "TGENEMENUSUBLEVEL";
        } 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 getSubLevelCode(Integer menucode, Integer levelcode) {
        Integer sublevelcode = 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(SUBLEVEL), 0)+1 from TGENEMENUSUBLEVEL where MENUCODE = " + menucode + " and LEVELCODE = " + levelcode);

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

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

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