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

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.save.DtoSave;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.gene.TgeneParameters;

/**
 * Clase controladora del lov asociado al bean TgeneParameters.
 *
 * @author WPA.
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class ParametersController extends AbstractController<TgeneParameters> {

    private static final long serialVersionUID = 1L;

    public ParametersController() throws Exception {
        super(TgeneParameters.class);
    }

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        //
        super.addFilter("pk.companycode", super.getLoginController().getRequest().getCompany().toString());

    }

    /**
     * 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 = "PARAMETERS";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void update() {
        try {
            this.record.getPk().setCompanycode(super.getLoginController().getRequest().getCompany());
            super.update();
        } catch (Exception ex) {
            MessageHelper.setMessageError(ex);
        }
    }

    public void update(TgeneParameters bean) {
        try {
            this.record = bean;
            super.update();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            Request request = this.callerhelper.getRequest();

            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.pk.code"); // En en string van todos los campos de orden ("t.pk,  t.nombre, t.cpais").

            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<TgeneParameters>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneParameters>) 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);
        }
    }

    /**
     * Entrega un objeto TgeneParameters
     *
     * @param code C&oacute de par&aacute;metro
     * @param companycode C&oacute;digo de compania
     * @return record Objetos TgeneParameters
     */
    public static TgeneParameters find(String code, String companycode) {
        try {
            ParametersController cc = new ParametersController();
            cc.init();
            cc.recperpage = 10;
            cc.addFilter("pk.code", code);
            cc.addFilter("pk.companycode", companycode);
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }

    }
    
    /** ==================================== GUARDAR PARAMETROS ====================*/
    public void updateParametro(TgeneParameters bean) throws Exception {
        this.record = bean;
        //this.update();
        super.update();
        this.save();
    }
    
    
    
    

    
}
