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

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.controller.pgeneral.gene.AreaController;
import com.fp.frontend.controller.pgeneral.gene.BranchController;
import com.fp.frontend.controller.pgeneral.gene.OfficeController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.gene.TgeneArea;
import com.fp.persistence.pgeneral.gene.TgeneBranch;
import com.fp.persistence.pgeneral.gene.TgeneOffice;
import com.fp.persistence.pgeneral.safe.TsafeTerminal;

/**
 * Clase controladora del bean TsafeTerminal.
 *
 * @author David L&oacute;pez P.
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class TerminalController extends AbstractController<TsafeTerminal> {

    private static final long serialVersionUID = 1L;

    public TerminalController() throws Exception {
        super(TsafeTerminal.class);
    }
    /**
     * Atributo para la lista de sucursales
     */
    private List<TgeneBranch> lbranch;
    /**
     * Atributo para la lista de oficinas
     */
    private List<TgeneOffice> loffice;
    /**
     * Atributo para la lista de areas
     */
    private List<TgeneArea> larea;
    /**
     * Atrubuto V/F
     */
    private boolean activate;

    @PostConstruct
    private void postconstruct() {
        this.init();
        super.startQuery();
        //Listas
        this.lbranch = BranchController.find(super.getLoginController().getRequest().getCompany().toString());
        this.larea = AreaController.find(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 = "TERMINAL";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Entrega el valor de: lbranch
     *
     * @return List<TgeneBranch>
     */
    public List<TgeneBranch> getLbranch() {
        return lbranch;
    }

    /**
     * Entrega el valor de: loffice
     *
     * @return List<TgeneOffice>
     */
    public List<TgeneOffice> getLoffice() {
        return loffice;
    }

    /**
     * Entrega el valor de: larea
     *
     * @return List<TgeneArea>
     */
    public List<TgeneArea> getLarea() {
        return larea;
    }

    /**
     * Crea una instancia de TsafeProfileHorary y marca el registro como nuevo.
     *
     * @throws Exception
     */
    @Override
    public void create() throws Exception {
        if (super.getMfilters().get("branchcode") == null || getMfilters().get("officecode") == null || super.getMfilters().get("areacode") == null) {
            MessageHelper.setMessageError("msg_filterrequird");
            return;
        }
        super.create();
        this.record.getPk().setCompanycode(super.getLoginController().getRequest().getCompany());
        this.record.setBranchcode(Integer.valueOf(super.getMfilters().get("branchcode")));
        this.record.setOfficecode(Integer.valueOf(super.getMfilters().get("officecode")));
        this.record.setAreacode(Integer.valueOf(super.getMfilters().get("branchcode")));

    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        if ((super.getMfilters().get("branchcode") == null || getMfilters().get("officecode") == null || super.getMfilters().get("areacode") == null) && !this.activate) {
            MessageHelper.setMessageError("msg_filterrequird");
            return;
        }
        try {
            if (!this.activate) {
                super.addFilter("pk.companycode", super.getLoginController().getRequest().getCompany().toString());
            }
            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.pk.terminalcode");

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

    @Override
    public void postCommit(Response response) throws Exception {
        super.postCommitGeneric(response, this.beanalias);
    }

    public void loadOffice() {
        this.loffice = OfficeController.find(super.getMfilters().get("branchcode"), super.getLoginController().getRequest().getCompany().toString());
    }

    /**
     * Entrega una lista de objetos TsafeTerminal
     *
     * @param companycode C&oacute;digo de la compania
     * @return lrecord Lista de objetos TgeneCatalogDetail
     */
    public static List<TsafeTerminal> find(String companycode) {
        try {
            TerminalController cc = new TerminalController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.companycode", companycode);
            cc.activate = true;
            cc.querydatabase();
            if (cc.lrecord != null && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }

    }
}
