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

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

    private static final long serialVersionUID = 1L;

    public OfficeController() throws Exception {
        super(TgeneOffice.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 = "TGENEOFFICE";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Inicializa las paginas en la consulta
     */
    public void initRecPage() {
        this.page = 0;
        this.recperpage = 10;
    }

    /**
     * Crea una instancia de TgeneTransactionProcess y marca el registro como
     * nuevo.
     *
     * @throws Exception
     */
    @Override
    public void create() throws Exception {
        if (super.getMfilters().get("pk.branchcode") == null || super.getMfilters().get("pk.branchcode").equals("")) {
            MessageHelper.setMessageError("msg_branchRequired");
            return;
        }
        super.create();
        this.record.put("branchdesc", super.getMfilelds().get("branchdesc"));
        this.record.getPk().setCompanycode(super.getLoginController().getRequest().getCompany());
        this.record.getPk().setBranchcode(new Integer(super.getMfilters().get("pk.branchcode")));
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            if (super.getMfilters().get("pk.branchcode") == null) {
                MessageHelper.setMessageError("msg_branchRequired");
                return;
            }
            if (super.getMfilters().get("pk.companycode") == null || super.getMfilters().get("pk.companycode").equals("")) {
                super.addFilter("pk.companycode", super.getLoginController().getRequest().getCompany().toString());
            }

            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.pk.officecode");

            // subqueries
            SubQuery subquery = new SubQuery("TgeneBranch", "description", "branchdesc",
                    "i.pk.companycode = t.pk.companycode and i.pk.branchcode = t.pk.branchcode");
            dto.addSubQuery(subquery);

            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<TgeneOffice>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneOffice>) 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 static List<TgeneOffice> find(String branch, String companycode) {
        try {
            OfficeController oc = new OfficeController();
            oc.init();
            oc.recperpage = 300;
            oc.addFilter("pk.branchcode", branch);
            oc.addFilter("pk.companycode", companycode);
            oc.querydatabase();
            if (oc.lrecord != null && !oc.lrecord.isEmpty()) {
                return oc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }

    }
}
