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.AbstractDataTransport;
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.gene.ChannelController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.gene.TgeneChannels;
import com.fp.persistence.pgeneral.safe.TsafePassword;

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

    private static final long serialVersionUID = 1L;

    public PasswordController() throws Exception {
        super(TsafePassword.class);
    }

    /**
     * Atributo para la lista de objetos TgeneChannels
     */
    private List<TgeneChannels> lchannels;

    private boolean active;

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        this.lchannels = ChannelController.find();

    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza
     * el controlador.
     */
    public void init() {
        try {
            this.recperpage = 10; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.record = null;
            this.beanalias = "PASSWORD";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    public void execute() {
        this.active = true;
        this.querydatabase();
    }

    @Override
    public void create() {
        try {
            super.create();
            this.record.getPk().setCompanycode(super.getLoginController().getRequest().getCompany());
            this.record.getPk().setChannelcode(super.getMfilters().get("pk.channelcode"));

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

    @Override
    protected void querydatabase() {
        try {
            if (!this.existAtLeastOneFilterValue()) {
                MessageHelper.setMessageError("msg_filterrequird");
                return;
            }
            Request request = this.callerhelper.getRequest();
            super.addFilter("pk.companycode", super.getLoginController().getRequest().getCompany().toString());

            DtoQuery dto = super.getDtoQuery(false);
            dto.setOrderby("t.pk.channelcode"); // 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.record = new TsafePassword();
                MessageHelper.setMessageError(resp);
            } else {
                this.record = (TsafePassword) resp.get(this.beanalias);
                if (this.record != null) {
                    super.postQuery((AbstractDataTransport) resp.get(this.beanalias));
                } else {
                    this.create();
                }
            }

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

    @Override
    public void save() {
        try {
            if (!this.existAtLeastOneFilterValue()) {
                MessageHelper.setMessageError("msg_filterrequird");
                return;
            }
            if (this.record.getPk().getCompanycode() == null || this.record.getPk().getCompanycode().compareTo(0) == 0) {
                MessageHelper.setMessageError("msg_querydata");
                return;
            }
            Request request = this.callerhelper.getRequest();
            super.update();
            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 postCommit(Response response) throws Exception {
        super.postCommitGeneric(response, this.beanalias);
    }

    /**
     * Entrega una lista de objetos TgeneChannels
     *
     * @return lchannels Lista de objetos TgeneChannels
     */
    public List<TgeneChannels> getLchannels() {
        return lchannels;
    }

    /**
     * Fija una lista de objetos TgeneChannels
     *
     * @param lchannels Lista de objetos TgeneChannels
     */
    public void setLchannels(List<TgeneChannels> lchannels) {
        this.lchannels = lchannels;
    }

    /**
     * Entrega V/F
     *
     * @return active V/F
     */
    public boolean isActive() {
        return active;
    }

    /**
     * Fija V/F
     *
     * @param active V/F
     */
    public void setActive(boolean active) {
        this.active = active;
    }

}
