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 javax.faces.event.AjaxBehaviorEvent;

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.pcustomer.PersonDetailController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.parmas.soli.TarmGuardias;

/**
 * Controlador que maneja guardias de seguridad
 *
 * @author james
 *
 */
@ManagedBean
@ViewScoped
public class GuardiasController extends AbstractController<TarmGuardias> {

    private static final long serialVersionUID = 1L;

    public GuardiasController() throws Exception {
        super(TarmGuardias.class);
    }

    private void init() {
        try {
            this.recperpage = 15; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "GUARDIAS";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * M&eacute;todo ejecutado despu&eacute;s de ejecutarse el constructor
     */
    @PostConstruct
    public void postConstruct() {

        init();
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            DtoQuery dtoQuery = super.getDtoQuery(Boolean.TRUE);
            HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
            mtables.put(beanalias, dtoQuery);
            SubQuery subQueryGuardia1 = new SubQuery("TcustPersonDetail", "name", "gnombre", "i.pk.personcode=t.pk and  i.pk.dateto=(select max(dt.pk.dateto) from TcustPersonDetail dt where dt.pk.personcode=t.pk)");
            SubQuery subQueryGuardia2 = new SubQuery("TcustPersonDetail", "identification", "gcedula", "i.pk.personcode=t.pk and  i.pk.dateto=(select max(dt.pk.dateto) from TcustPersonDetail dt where dt.pk.personcode=t.pk)");
            SubQuery subQueryEmpresa1 = new SubQuery("TcustPersonDetail", "name", "nempresa", "i.pk.personcode=t.cempresa and i.pk.dateto=(select max(dt.pk.dateto) from TcustPersonDetail dt where dt.pk.personcode=t.cempresa)");
            SubQuery subQueryEmpresa2 = new SubQuery("TcustPersonDetail", "identification", "iempresa", "i.pk.personcode=t.cempresa and  i.pk.dateto=(select max(dt.pk.dateto) from TcustPersonDetail dt where dt.pk.personcode=t.cempresa)");
            dtoQuery.addSubQuery(subQueryGuardia1);
            dtoQuery.addSubQuery(subQueryGuardia2);
            dtoQuery.addSubQuery(subQueryEmpresa1);
            dtoQuery.addSubQuery(subQueryEmpresa2);
            Request request = callerhelper.getRequest();
            request.setQueryTables(mtables);
            Response response = callerhelper.executeQuery(request);
            if (response.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                this.lrecord = new ArrayList<>();
                MessageHelper.setMessageError(response);
            } else {
                this.lrecord = (List<TarmGuardias>) response.get(beanalias);
                this.postQuery(lrecord);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * M\u00e9todo para encontrar por solicitud
     *
     * @param solicitudCode
     * @return
     */
    public static TarmGuardias find(String guardiaCode, String empresaCode) {
        try {
            GuardiasController cc = new GuardiasController();
            //cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk", guardiaCode);
            cc.addFilter("cempresa", empresaCode);
            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

    @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 response = this.callerhelper.executeSave(request);
            if (response.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {
                this.postCommit(response);
                MessageHelper.setMessageInfo(response);
            } else {
                MessageHelper.setMessageError(response);
            }

        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Seleccionado todos los registros de la tabla
     */
    public void seleccionarTodos(AjaxBehaviorEvent event) {
        try {
            Boolean valorColocar = Boolean.FALSE;
            if (Boolean.valueOf(event.getComponent().getAttributes().get("value") != null ? event.getComponent().getAttributes().get("value").toString() : "false")) {
                valorColocar = Boolean.TRUE;
            }
            for (TarmGuardias guardias : lrecord) {
                guardias.getModifiedData().put("seleccionado", valorColocar);
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    public static TarmGuardias findxcguardia(String codigopersona) {
        try {
            GuardiasController cc = new GuardiasController();
            cc.init();
            cc.recperpage = 300;
            cc.addFilter("pk", codigopersona);

            cc.querydatabase();
            if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
                return cc.lrecord.get(0);
            }
            return null;
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
            return null;
        }
    }

}
