package com.fp.frontend.controller.security;

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.controller.pgeneral.menu.MenuController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.menu.TgeneMenu;
import com.fp.persistence.pgeneral.menu.TgeneMenuProfile;
import com.fp.persistence.pgeneral.safe.TsafeProfile;

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

    private static final long serialVersionUID = 1L;

    public MenuProfileController() throws Exception {
        super(TgeneMenuProfile.class);
    }

    private List<TsafeProfile> lprofile;
    private List<TgeneMenu> lMenu;

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        //Listas
        this.lprofile = ProfileController.find();
        this.lMenu = MenuController.find();

    }

    /**
     * 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.create();
            this.lrecord = new ArrayList<>();
            this.beanalias = "TGENEMENUPROFILE";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {

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

            // subqueries 1
            SubQuery subquery1 = new SubQuery("TsafeProfile", "description", "profiledesc",
                    "i.pk = t.pk");
            dto.addSubQuery(subquery1);

            // subqueries 2
            SubQuery subquery2 = new SubQuery("TgeneMenu", "description", "menudesc",
                    "i.pk = t.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<TgeneMenuProfile>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneMenuProfile>) 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);
        }
    }

    @Override
    public void create() throws Exception {
        super.create();
        this.record.setPk(super.getMfilters().get("pk"));
    }

    /**
     * Entrega una lista de objetos TbpmGroups
     *
     * @param companycode C&oacute;digo de compania
     * @return lrecord Lista de objetos TbpmGroups
     */
    public static List<TgeneMenuProfile> find() {
        try {
            MenuProfileController cc = new MenuProfileController();
            cc.init();
            cc.recperpage = 300;
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }

    }

    /**
     * Fija la descripcion del perfil en el record
     */
    public void setProfileDesc() {
        for (TsafeProfile p : this.lprofile) {
            if (p.getPk().compareTo(this.record.getPk()) == 0) {
                this.record.put("profiledesc", p.getDescription());
            }
        }
    }

    /**
     * Fija la descripcion del menu en el record
     */
    public void setMenuDesc() {
        for (TgeneMenu m : this.lMenu) {
            if (m.getPk().compareTo(this.record.getMenucode()) == 0) {
                this.record.put("menudesc", m.getDescription());
            }
        }
    }

    /**
     * Entrega una lista de objetos TsafeProfile
     *
     * @return lprofile
     */
    public List<TsafeProfile> getLprofile() {
        return this.lprofile;
    }

    /**
     * Fija una lista de objetos TsafeProfile
     *
     * @param lprofile
     */
    public void setLprofile(List<TsafeProfile> lprofile) {
        this.lprofile = lprofile;
    }

    /**
     * Entrega una lista de objetos TgeneMenu
     *
     * @return lMenu
     */
    public List<TgeneMenu> getlMenu() {
        return this.lMenu;
    }

    /**
     * Fija una lista de objetos TgeneMenu
     *
     * @param lMenu
     */
    public void setlMenu(List<TgeneMenu> lMenu) {
        this.lMenu = lMenu;
    }
}
