package com.fp.frontend.controller.armas.parametros;

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

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

import org.primefaces.event.SelectEvent;

import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.controller.pgeneral.lov.CatalogLovController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.gene.TgeneCatalog;
import com.fp.persistence.pgeneral.gene.TgeneCatalogDetail;

/**
 * Clase controladora del bean TgeneCatalogDetail.
 *
 * @author Jorge Vaca.
 * @version 2.1
 */
@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class SancionesController extends AbstractController<TgeneCatalogDetail> {

    public SancionesController() throws Exception {
        super(TgeneCatalogDetail.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 = 15; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "CATALOGDETAIL";
        } catch (Exception 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.catalogcode") == null) {
            MessageHelper.setMessageError("msg_catalogrequird");
            return;
        }
        super.create();
        this.record.getPk().setCatalogcode(super.getMfilters().get("pk.catalogcode"));
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.description");

            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(this.beanalias, dto); // permite adicionar mas de una tabla.

            Request request = this.callerhelper.getRequest();
            request.setQueryTables(mtables);

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

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.lrecord = new ArrayList<TgeneCatalogDetail>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneCatalogDetail>) resp.get(this.beanalias);
                super.postQuery(this.lrecord);
            }

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

    @Override
    public void save() {
        try {
            DtoSave dtosave = super.getDtoSave();
            dtosave.setReturnpk(true); // Para que el core devuelva el pk de los registros nuevos.
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();

            Request request = this.callerhelper.getRequest();
            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);
        }
    }

    public void openCatalogLov() {
        Map<String, List<String>> params = new HashMap<>();
        CatalogLovController.openLov(params);
    }

    public void onReturnCatalogLov(SelectEvent event) throws Exception {
        TgeneCatalog t = (TgeneCatalog) event.getObject();
        super.addFilter("pk.catalogcode", t.getPk());
        super.addField("catalogname", t.getDescription());
        this.query();
    }

    /**
     * Entrega una lista de objetos TgeneCatalogDetail
     *
     * @param catalogcode C&oacute de cat&aacute;logo
     * @return lrecord Lista de objetos TgeneCatalogDetail
     */
    public static List<TgeneCatalogDetail> find(String catalogcode) {
        try {
            SancionesController cc = new SancionesController();
            cc.init();
            cc.recperpage = 10000;
            cc.addFilter("pk.catalogcode", catalogcode);
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    /**
     * Entrega una lista de objetos TgeneCatalogDetail
     *
     * @param catalogcode C&oacute de cat&aacute;logo
     * @param legalcode C&oacute;digo legal
     * @return lrecord Lista de objetos TgeneCatalogDetail
     */
    public static List<TgeneCatalogDetail> find(String catalogcode, String legalcode) {
        try {
            SancionesController cc = new SancionesController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.catalogcode", catalogcode);
            cc.addFilter("legalcode", legalcode);
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    /**
     * Metodo que consulta por Catalog y Catalogcode ambos requeridos
     */
    public static TgeneCatalogDetail findxCodigoCodcatalogo(String catalog, String catalogcode) {
        try {//TgeneCatalogDetailKey
            if (catalog != null && catalogcode != null) {
                SancionesController cc = new SancionesController();
                cc.init();
                cc.recperpage = 300;
                cc.addFilter("pk.catalogcode", catalogcode);
                cc.addFilter("pk.catalog", catalog);
                cc.querydatabase();
                if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                    return cc.lrecord.get(0);
                }
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    public static TgeneCatalogDetail findxCodigo(String catalog) {
        try {//TgeneCatalogDetailKey
            SancionesController cc = new SancionesController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.catalog", catalog);
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    /**
     * Metodo que llena lal lista de g&eacute;neros
     */
    public static List<String[]> getListGender() {
        List<String[]> gender = new ArrayList<String[]>();
        String[] male = {"M", "MASCULINO"};
        String[] female = {"F", "FEMENINO"};
        gender.add(male);
        gender.add(female);
        return gender;
    }
}
