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

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 org.primefaces.context.RequestContext;

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.armas.parametros.GuardiasController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.parmas.soli.TarmGuardias;
import com.fp.persistence.parmas.soli.TarmSolicitudGuardias;

@ManagedBean
@ViewScoped
public class SolicitudGuardiasController extends AbstractController<TarmSolicitudGuardias> {

    private static final long serialVersionUID = 1L;

    public SolicitudGuardiasController() throws Exception {
        super(TarmSolicitudGuardias.class);
    }

    /**
     * M&eacute;todo que se ejecuta despues del controlador
     */
    @PostConstruct
    public void postConstruct() {
        this.init();
        super.startQuery();
        this.getMfilters().clear();
    }

    /**
     * Inicializa variables
     */
    private void init() {
        try {
            recperpage = 300; // Cambiar al # reg a mirar.
            lrecord = new ArrayList<>();
//            record = new TarmSolicitudGuardias();
            beanalias = "SOLICITUDGUARDIAS";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            DtoQuery dtoQuery = super.getDtoQuery(Boolean.TRUE);
            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            dtoQuery.setOrderby("pk.csolicitud");
            mtables.put(beanalias, dtoQuery);
            Request request = this.callerhelper.getRequest();
            request.setQueryTables(mtables);
            Response response = this.callerhelper.executeQuery(request);
            if (response.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.lrecord = new ArrayList<TarmSolicitudGuardias>();
                MessageHelper.setMessageError(response);
            } else {
                this.lrecord = (List<TarmSolicitudGuardias>) response.get(beanalias);
                for (TarmSolicitudGuardias tarmSolicitudGuardias : this.lrecord) {
                    TarmGuardias guardia = new TarmGuardias();
                    guardia = GuardiasController.find(String.valueOf(tarmSolicitudGuardias.getPk().getCguardia()), String.valueOf(tarmSolicitudGuardias.getPk().getCempresa()));
                    //tarmSolicitudGuardias.modifiedData().put("guardia",guardia!=null?guardia:new TarmGuardias());
                    tarmSolicitudGuardias.modifiedData().put("nombre", guardia == null ? "" : guardia.getModifiedData().get("gnombre"));
                    tarmSolicitudGuardias.modifiedData().put("identificador", guardia == null ? "" : guardia.getModifiedData().get("gcedula"));
                    tarmSolicitudGuardias.modifiedData().put("estado", guardia == null ? "" : guardia.getEstado());
                    tarmSolicitudGuardias.modifiedData().put("guardia", guardia == null ? "" : guardia.getPk());

                }
                super.postQuery(this.lrecord);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    protected void querydatabaseGuardia() {
        try {
            DtoQuery dtoQuery = super.getDtoQuery(Boolean.TRUE);
            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(beanalias, dtoQuery);
            Request request = this.callerhelper.getRequest();
            request.setQueryTables(mtables);
            Response response = this.callerhelper.executeQuery(request);
            if (response.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.lrecord = new ArrayList<TarmSolicitudGuardias>();
                MessageHelper.setMessageError(response);
            } else {
                this.lrecord = (List<TarmSolicitudGuardias>) response.get(beanalias);
                for (TarmSolicitudGuardias tarmSolicitudGuardias : this.lrecord) {
                    TarmGuardias guardia = new TarmGuardias();
                    guardia = GuardiasController.find(String.valueOf(tarmSolicitudGuardias.getPk().getCguardia()), String.valueOf(tarmSolicitudGuardias.getPk().getCempresa()));
                    //tarmSolicitudGuardias.modifiedData().put("guardia",guardia!=null?guardia:new TarmGuardias());
                    tarmSolicitudGuardias.modifiedData().put("nombre", guardia == null ? "" : guardia.getModifiedData().get("gnombre"));
                    tarmSolicitudGuardias.modifiedData().put("identificador", guardia == null ? "" : guardia.getModifiedData().get("gcedula"));
                    tarmSolicitudGuardias.modifiedData().put("estado", guardia == null ? "" : guardia.getModifiedData().get("estado"));

                }
                super.postQuery(this.lrecord);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Retorna guardias en base a un criterio
     *
     * @param solicitudCode c&oacute;digo de la solicitud
     * @return
     */
    public List<TarmSolicitudGuardias> findPorSolicitud(String solicitudCode) {
        try {
            SolicitudGuardiasController cc = new SolicitudGuardiasController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk.csolicitud", solicitudCode);
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    /**
     * Devuelve todas las solicitudes encontradas
     *
     * @return
     */
    public static List<TarmSolicitudGuardias> find() {
        try {
            SolicitudGuardiasController cc = new SolicitudGuardiasController();
            cc.init();
            cc.recperpage = 300;
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord;
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }

    }

    @Override
    public void save() {
        try {
            DtoSave dtoSave = super.getDtoSave();
            dtoSave.setReturnpk(Boolean.TRUE);
            if (!dtoSave.pendingProcess()) {
                return;
            }
            HashMap<String, DtoSave> msaves = new HashMap<String, DtoSave>();
            msaves.put(beanalias, dtoSave);
            Request request = callerhelper.getRequest();
            request.setSaveTables(msaves);
            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);
        }
    }

    /**
     * M&eacute;todo para el inicio de flujo
     */
    public void completarTarea() {

        try {
            Request request = callerhelper.getRequest();
            // limpiar request para finalizar la tarea.
            super.cleanRequest(request);
            request.modifiedData().put("pk.csolicitud", "1");
            request.modifiedData().put("csolicitud", "1");
            request.modifiedData().put("TID", tid);
            request.modifiedData().put("BPMStatus", bpmDataStatus == null ? "A" : bpmDataStatus); // A,D,R
            request.modifiedData().put("BPMObs", bpmDataComment == null ? "OK" : bpmDataComment);

            Response resp = callerhelper.executeSave(request);

            if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {
                MessageHelper.setMessageInfo(resp);
                RequestContext.getCurrentInstance().execute("Maia.refreshusertasks()");
            } else {
                MessageHelper.setMessageError(resp);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

}
