package com.fp.frontend.controller.armas.parametros;

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.Filter;
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.parmas.fun.TarmVentaArmaTem;

@ManagedBean
@ViewScoped
public class TarmVentaArmaTemporalController extends AbstractController<TarmVentaArmaTem> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public TarmVentaArmaTemporalController() throws Exception {
        super(TarmVentaArmaTem.class);
    }

    @PostConstruct
    private void postconstruct() {
        this.init();
        super.startQuery();
    }

    private void init() {
        try {
            recperpage = 15;
            lrecord = new ArrayList<>();
            beanalias = "VENTAARMATEMPORAL";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            DtoQuery dto = super.getDtoQuery(true);
            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(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) {
                lrecord = new ArrayList<TarmVentaArmaTem>();
                MessageHelper.setMessageError(resp);
            } else {
                lrecord = (List<TarmVentaArmaTem>) resp.get(beanalias);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @Override
    public void save() {
        try {
            DtoSave dtosave = super.getDtoSave();
            dtosave.setReturnpk(true);
            HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();

            Request request = callerhelper.getRequest();
            msave.put(beanalias, dtosave);

            request.setSaveTables(msave);
            Response resp = 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);
        }
    }

    public static TarmVentaArmaTem findPendienteCarma(String carma) {
        try {
            TarmVentaArmaTemporalController cc = new TarmVentaArmaTemporalController();
            cc.init();
            cc.recperpage = 5000;
            if (carma != null && !carma.isEmpty()) {
                cc.addFilter("carma", carma);
            }
            cc.addFilter("estado", "PENDIENTE");
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    public static List<TarmVentaArmaTem> findLote(String lote) {
        try {
            TarmVentaArmaTemporalController cc = new TarmVentaArmaTemporalController();
            cc.init();
            cc.recperpage = 5000;
            cc.addFilter("estado", "APROBADO");
            cc.querydatabaselote(lote);
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    protected void querydatabaselote(String lote) {
        try {
            DtoQuery dto = this.getDtoQueryLote();
            dto.setOrderby("pk");
            String sqlFinal = " t.carma in (select p.pk from TarmArmas p where p.lote='" + lote + "') ";
            Filter filtroFinal = new Filter();
            filtroFinal.setSql(sqlFinal);
            dto.addFiltro(filtroFinal);

            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(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) {
                lrecord = new ArrayList<TarmVentaArmaTem>();
                MessageHelper.setMessageError(resp);
            } else {
                lrecord = (List<TarmVentaArmaTem>) resp.get(beanalias);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    private DtoQuery getDtoQueryLote() throws Exception {
        DtoQuery dto = super.getDtoQuery(true);
        SubQuery subqueryTipoFab = new SubQuery("TgeneCatalogDetail", "description", "tipofabricacion", "i.pk.catalog= (select p.tipofabricacion from TarmArmas p where p.pk=t.carma)"//t.tipofabricacion
                + " and i.pk.catalogcode='TIPOFABRICACION'");
        dto.addSubQuery(subqueryTipoFab);
        SubQuery subqueryTipo = new SubQuery("TgeneCatalogDetail", "description", "tipo", "i.pk.catalog=    (select o.tipoarmaexplosivo       from TarmTipoArmaExplosivo o "
                + " where o.pk=(select p.ctipoarmaexplosivo from TarmArmas p where p.pk=t.carma)) "//t.ctipoarmaexplosivo
                + " and "
                + " i.pk.catalogcode=(select o.tipoarmaexplosivocodigo from TarmTipoArmaExplosivo o "
                + " where o.pk=(select p.ctipoarmaexplosivo from TarmArmas p where p.pk=t.carma))");//t.ctipoarmaexplosivo
        dto.addSubQuery(subqueryTipo);
        SubQuery subqueryClasecatalogo = new SubQuery("TgeneCatalogDetail", "description", "clase", "i.pk.catalog=    (select o.clase       from TarmTipoArmaExplosivo o "
                + " where o.pk=(select p.ctipoarmaexplosivo from TarmArmas p where p.pk=t.carma))"//t.ctipoarmaexplosivo
                + " and "
                + " i.pk.catalogcode=(select o.clasecodigo from TarmTipoArmaExplosivo o "
                + " where o.pk=(select p.ctipoarmaexplosivo from TarmArmas p where p.pk=t.carma))");//t.ctipoarmaexplosivo
        dto.addSubQuery(subqueryClasecatalogo);
        return dto;
    }
}
