package com.fp.frontend.controller.bpm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.event.SelectEvent;

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.lov.TransactionLovController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pbpm.gene.TbpmField;
import com.fp.persistence.pbpm.gene.TbpmFieldTransactionOrigin;
import com.fp.persistence.pgeneral.trans.TgeneTransaction;

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

    private static final long serialVersionUID = 1L;

    public FieldTransactionOriginController() throws Exception {
        super(TbpmFieldTransactionOrigin.class);
    }

    /**
     * Atributo para la lista de objetos TbpmField
     */
    private List<TbpmField> lfield;

    @PostConstruct
    private void postconstruct() {
        this.init();
        // Inicializa autoconsulta
        super.startQuery();
        //Listas
        this.lfield = FieldsController.find();
    }

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

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {

            if (super.getMfilters().get("pk.transactionmodule") == null) {
                MessageHelper.setMessageError("msg_catalogrequird");
                return;
            }

            Request request = this.callerhelper.getRequest();
            DtoQuery dto = super.getDtoQuery(true);
            dto.setOrderby("t.pk.fieldname");

            //Subquery
            SubQuery subquery = new SubQuery("TbpmField", "description", "descriptionfield", "i.pk = t.pk.fieldname");
            dto.addSubQuery(subquery);

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

    @Override
    public void create() throws Exception {
        if (super.getMfilters().get("pk.transactionmodule") == null) {
            MessageHelper.setMessageError("msg_catalogrequird");
            return;
        }
        super.create();
        this.record.getPk().setTransactionmodule(super.getMfilters().get("pk.transactionmodule"));
        this.record.getPk().setTransactioncode(new Integer(super.getMfilters().get("pk.transactioncode")));
        this.record.getPk().setTransactionversion(new Integer(super.getMfilters().get("pk.transactionversion")));
    }

    @Override
    public void update() throws Exception {
        if (super.getMfilters().get("pk.transactionmodule") == null) {
            MessageHelper.setMessageError("msg_catalogrequird");
            return;
        }
        super.update();
    }

    /**
     * Abre el lov de transacciones
     */
    public void openTransactionLov() {
        Map<String, List<String>> params = new HashMap<>();
        List<String> l = new ArrayList<>();
        l.add("TRANSACTION"); // valor del parametro
        params.put("processtype", l);

        TransactionLovController.openLov(params);
    }

    /**
     * Gestiona la respuesta del lov
     *
     * @param event
     * @throws Exception
     */
    public void onReturnTransactionLov(SelectEvent event) throws Exception {
        TgeneTransaction t = (TgeneTransaction) event.getObject();
        super.addFilter("pk.transactionmodule", t.getPk().getTransactionmodule());
        super.addFilter("pk.transactioncode", t.getPk().getTransactioncode().toString());
        super.addFilter("pk.transactionversion", t.getPk().getTransactionversion().toString());
        super.addField("transactionname", t.getName());
        this.query();
    }

    /**
     * Controla el combo
     */
    public void onChangeField() {
        if (this.record.getPk().getFieldname() != null) {
            for (TbpmField field : this.lfield) {
                if (this.record.getPk().getFieldname().compareTo(field.getPk()) == 0) {
                    this.record.put("descriptionfield", field.getDescription());
                }
            }
        } else {
            this.record.put("descriptionfield", null);
        }
    }

    /**
     * Entrega una lista de objetos TbpmField
     *
     * @return lfield Lista de objetos TbpmField
     */
    public List<TbpmField> getLfield() {
        return lfield;
    }

    /**
     * Fija una lista de objetos TbpmField
     *
     * @param lfield Lista de objetos TbpmField
     */
    public void setLfield(List<TbpmField> lfield) {
        this.lfield = lfield;
    }

}
