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

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.controller.pgeneral.gene.CurrencyController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pgeneral.gene.TgeneCurrency;
import com.fp.persistence.pgeneral.product.TgeneModule;
import com.fp.persistence.pgeneral.product.TgeneProduct;
import com.fp.persistence.pgeneral.product.TgeneSubProduct;
import com.fp.persistence.pgeneral.product.TgeneSubProductCurrency;

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

    List<TgeneModule> lmodules;
    List<TgeneCurrency> lcurrency;
    List<TgeneProduct> lproduct;
    List<TgeneSubProduct> lsubproduct;

    public SubProductCurrencyController() throws Exception {
        super(TgeneSubProductCurrency.class);
    }

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        this.lmodules = ModuleController.find();
        this.lcurrency = CurrencyController.find();
    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza
     * el controlador.
     */
    private void init() {
        try {
            this.recperpage = 500; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "SUBPRODUCTCURRENCY";
            this.lproduct = new ArrayList<>();
            this.lsubproduct = new ArrayList<>();
        } 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 {
        super.create();
        this.record.getPk().setModulecode(super.getMfilters().get("pk.modulecode"));
        this.record.getPk().setProductcode(super.getMfilters().get("pk.productcode"));
        this.record.getPk().setSubproductcode(super.getMfilters().get("pk.subproductcode"));
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            String module = super.getMfilters().get("pk.modulecode");
            String product = super.getMfilters().get("pk.productcode");
            String subproduct = super.getMfilters().get("pk.subproductcode");
            if ((module == null) || module.isEmpty()) {
                MessageHelper.setMessageError("msg_modulerequird");
                return;
            }
            if ((product == null) || product.isEmpty()) {
                MessageHelper.setMessageError("msg_productrequird");
                return;
            }
            if ((subproduct == null) || subproduct.isEmpty()) {
                MessageHelper.setMessageError("msg_subproductrequird");
                return;
            }

            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.pk.currencycode");
            // subqueries
            SubQuery subquery = new SubQuery("TgeneCurrency", "description", "currencydesc",
                    "i.pk = t.pk.currencycode");
            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<TgeneSubProductCurrency>();
                MessageHelper.setMessageError(resp);
            } else {
                this.lrecord = (List<TgeneSubProductCurrency>) 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<TgeneSubProductCurrency> find(String modulecode, String productcode, String subproductcode) {
        try {
            SubProductCurrencyController sc = new SubProductCurrencyController();
            sc.addFilter("pk.modulecode", modulecode);
            sc.addFilter("pk.productcode", productcode);
            sc.addFilter("pk.subproductcode", subproductcode);
            sc.init();
            sc.recperpage = 300;
            sc.querydatabase();
            if ((sc.lrecord != null) && !sc.lrecord.isEmpty()) {
                return sc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    public void changemodule() throws Exception {
        this.lproduct = ProductController.find(super.getMfilters().get("pk.modulecode"));
        this.lsubproduct = new ArrayList<>();
        this.lrecord = new ArrayList<>();
        super.getMfilters().put("pk.productcode", "");
        super.getMfilters().put("pk.subproductcode", "");
    }

    public void changeproduct() throws Exception {
        this.lsubproduct = SubProductController.find(super.getMfilters().get("pk.modulecode"), super.getMfilters().get("pk.productcode"));
        this.lrecord = new ArrayList<>();
        super.getMfilters().put("pk.subproductcode", "");
    }

    public void changesubproduct() throws Exception {
        //Metodo dummy es necesario para actualizar datos del filtro para ejecutar la consulta.
        this.querydatabase();
    }

    public void refreshCurrency() {
        for (TgeneCurrency obj : this.lcurrency) {
            if (obj.getPk().compareTo(this.record.getPk().getCurrencycode()) == 0) {
                this.record.modifiedData.put("currencydesc", obj.getDescription());
                break;
            }
        }
    }

    /**
     * Entrega el valor de: lmodules
     *
     * @return List<TgeneModule>
     */
    public List<TgeneModule> getLmodules() {
        return this.lmodules;
    }

    /**
     * Entrega el valor de: lproduct
     *
     * @return List<TgeneProduct>
     */
    public List<TgeneProduct> getLproduct() {
        return this.lproduct;
    }

    /**
     * Entrega el valor de: lsubproduct
     *
     * @return List<TgeneSubProduct>
     */
    public List<TgeneSubProduct> getLsubproduct() {
        return this.lsubproduct;
    }

    /**
     * Entrega el valor de: lcurrency
     *
     * @return List<TgeneCurrency>
     */
    public List<TgeneCurrency> getLcurrency() {
        return this.lcurrency;
    }

}
