/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arrebol.taxiservicios.controller.predio;

import com.arrebol.taxiservicios.controller.admin.*;
import com.arrebol.taxiservicios.controller.cobranza.CobranzaController;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.EstatusLote;
import com.arrebol.taxiservicios.model.enums.GenericEnumType;
import com.arrebol.taxiservicios.model.enums.PersonType;
import com.arrebol.taxiservicios.model.enums.TipoAbono;
import com.arrebol.taxiservicios.model.predio.AbonoLote;
import com.arrebol.taxiservicios.model.predio.AbonoProyecto;
import com.arrebol.taxiservicios.model.predio.DetalleLoteUrbanizacion;
import com.arrebol.taxiservicios.model.predio.Lote;
import com.arrebol.taxiservicios.model.predio.Manzana;
import com.arrebol.taxiservicios.model.predio.Predio;
import com.arrebol.taxiservicios.model.predio.proyectosLotesView;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Picasso
 */
public class PredioController extends GenericPersonController implements Serializable {

    private static final long serialVersionUID = -6265444716269535946L;

    final Logger logger = LogManager.getLogger(PredioController.class);

    public List<Person> fillProviderComboBox(Location location) {
        logger.info("Searching all providers to select..");

        List<Person> result = null;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
            Root<Person> root = criteria.from(Person.class);

            Path<String> idPath = root.get("id");
            Path<String> firstNamePath = root.get("firstName");
            Path<String> secondNamePath = root.get("secondName");
            Path<String> lastNamePath = root.get("lastName");
            Path<String> middleNamePath = root.get("middleName");

            criteria.select(
                    builder.construct(Person.class, idPath, firstNamePath, secondNamePath, lastNamePath, middleNamePath
                    ));
            Predicate criterioLocation = builder.equal(root.get("location"), location);
            Predicate predicate = builder.equal(root.get("personType"), PersonType.PROVIDER);
            Predicate predicate2 = builder.equal(root.get("active"), true);
            criteria.where(predicate, criterioLocation,builder.and(predicate2));

            result = session.createQuery(criteria).getResultList();

            logger.info("Total of providers found for ComboBox: " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Can not load list of providers for ComboBox ", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method fillProviderComboBox for Invoice", e);
        }

        return result;
    }

    public List<Predio> fillPredioDatatable() {

        Transaction transaction = null;
        List<Predio> result = null;

        try {
            logger.info("Searching all Predio..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<Predio> criteria = builder.createQuery(Predio.class);
            Root<Predio> root = criteria.from(Predio.class);

            criteria.where(builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED));
            criteria.orderBy(builder.asc(root.get("createdOn")));

            result = session.createQuery(criteria).getResultList();

            logger.info("Total of Predio found : " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load list of Predio ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillPredioDatatable of location", e);
            rollback(transaction);
        }

        return result;
    } 
    
    public List<Predio> fillPredioDatatableByLocation(Location location) {

        Transaction transaction = null;
        List<Predio> result = null;

        try {
            logger.info("Searching all Predio..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<Predio> criteria = builder.createQuery(Predio.class);
            Root<Predio> root = criteria.from(Predio.class);
            
            Predicate criterio1 = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);
            Predicate criterio2 = builder.equal(root.get("location"), location);

            criteria.where(builder.and(criterio1,criterio2));
            criteria.orderBy(builder.asc(root.get("createdOn")));

            result = session.createQuery(criteria).getResultList();

            logger.info("Total of Predio found : " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load list of Predio ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillPredioDatatable of location", e);
            rollback(transaction);
        }

        return result;
    } 
    
    public List<Predio> fillPredioByProveedor(String idProveedor) {
    
        Transaction transaction = null;
        List<Predio> result = null;

        try {
            logger.info("Searching all Predio..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<Predio> criteria = builder.createQuery(Predio.class);
            Root<Predio> root = criteria.from(Predio.class);

            
            
            criteria.where(builder.and(builder.equal(root.get("propetiario").get("id"), idProveedor),builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED)));
            
            criteria.orderBy(builder.asc(root.get("createdOn")));
            
            

            result = session.createQuery(criteria).getResultList();

            logger.info("Total of Predio found : " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load list of Predio ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillPredioDatatable of location", e);
            rollback(transaction);
        }

        return result;
    }
    
    public List<proyectosLotesView> fillProyectosLotesView(Location location) {
        Transaction transaction = null;
        List<proyectosLotesView> result = null;
        try {
            logger.info("Searching all proyectos lotes view..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<proyectosLotesView> criteria = builder.createQuery(proyectosLotesView.class);
            Root<proyectosLotesView> root = criteria.from(proyectosLotesView.class);  
            Predicate criterioLocation = builder.equal(root.get("location"), location);
            criteria.where(builder.and(criterioLocation));
            result = session.createQuery(criteria).getResultList();
            logger.info("Total of proyectos lotes view found : " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load list of proyectos lotes view ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillproyectosLotesView", e);
            rollback(transaction);
        }

        return result;
    }
    
     public List<AbonoProyecto> fillAbonoProyectoByPredio(Predio predio) {
        List<AbonoProyecto> resultList = null;
        Transaction transaction = null;
        try {
            logger.info("Searching for Lote..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<AbonoProyecto> criteria = builder.createQuery(AbonoProyecto.class);
            Root<AbonoProyecto> root = criteria.from(AbonoProyecto.class);

            Predicate criterio = (builder.equal(root.get("predio"), predio));
            Predicate criterio2 = (builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED));
            criteria.where(builder.and(criterio, criterio2));
            criteria.orderBy(builder.asc(root.get("fechaAPagar")));
            
            resultList = session.createQuery(criteria).getResultList();

            logger.info("Total of abonos found: " + (null == resultList ? -1 : resultList.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Abonos cannot be loaded " + e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillAbonoLoteByLote() " + e);
            rollback(transaction);
        }
        return resultList;
    }

    public Predio getPredioById(String predioId) {
        logger.info("getPersonById");

        Predio predio = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            predio = session.get(Predio.class, predioId);

            transaction.commit();
            logger.info("Predio " + predio);
        } catch (HibernateException e) {
            logger.error("Predio cannot be loaded " + predioId, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getPredioById(" + predioId + ") ", e);
            rollback(transaction);
        }
        return predio;
    }

    public boolean addPredio(Predio predio, User user, boolean save) {
        logger.info("addPredio");

        boolean success = false;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            if (save) {
                predio.setCreatedBy(user);
                predio.setCreatedOn(new Date());
                session.save(predio);
                transaction.commit();

                logger.info("Predio saved " + predio.getId());
            } else {
                predio.setLastUpdatedBy(user);
                session.update(predio);
                transaction.commit();
                logger.info("Predio updated " + predio.getId());
            }

            success = true;
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPredio() ", e);
            rollback(transaction);
        }
        return success;
    }

    public boolean addManzana(Manzana manzana, User user, boolean save) {
        logger.info("addManzana");

        boolean success = false;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            if (save) {
                manzana.setCreatedBy(user);
                manzana.setCreatedOn(new Date());
                manzana.setEstatusActivo(GenericEnumType.ENABLED);
                session.save(manzana);
                transaction.commit();

                logger.info("Manzana saved " + manzana.getId());
            } else {
                manzana.setLastUpdatedBy(user);
                session.update(manzana);
                transaction.commit();
                logger.info("Predio updated " + manzana.getId());
            }

            success = true;
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }

    public boolean addLote(Lote lote, User user, boolean save) {
        logger.info("addLote");

        boolean success = false;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            if (save) {
                lote.setCreatedBy(user);
                lote.setCreatedOn(new Date());
                lote.setEstatusActivo(GenericEnumType.ENABLED);
                lote.setMontoPagado(0D);
                session.save(lote);
                transaction.commit();

                logger.info("Lote saved " + lote.getId());
            } else {
                lote.setLastUpdatedBy(user);
                session.update(lote);
                transaction.commit();
                logger.info("Lote updated " + lote.getId());
            }

            success = true;
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean deleteAbonosLoteByLote(Lote lote, User user){
        logger.info("addLote");
        
        boolean success = false;

        Transaction transaction = null;
        
        try{
            
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            int update = session.createQuery("UPDATE AbonoLote "
                    + "SET estatusActivo = :estatusActivo, "
                    + " lastUpdatedBy = :user, "
                    + " lastUpdatedOn = :date "
                    
                    + "WHERE lote = :lote")
                    .setParameter("user", user)
                    .setParameter("date",new Date())
                    .setParameter("estatusActivo",GenericEnumType.DISABLED)
                    .setParameter("lote",lote)
                    .executeUpdate();

            transaction.commit();
            
            
           if(update > 0) success = true;
        
        
        
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean deleteLoteByManzana(Manzana manzana, User user){
        logger.info("addLote");
        
        boolean success = false;

        Transaction transaction = null;
        
        try{
            
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            int update = session.createQuery("UPDATE Lote "
                    + "SET estatusActivo = :estatusActivo, "
                    + " lastUpdatedBy = :user, "
                    + " lastUpdatedOn = :date "
                    
                    + "WHERE manzana = :manzana")
                    .setParameter("user", user)
                    .setParameter("date",new Date())
                    .setParameter("estatusActivo",GenericEnumType.DISABLED)
                    .setParameter("manzana",manzana)
                    .executeUpdate();

            transaction.commit();
            
            
           if(update > 0) success = true;
        
        
        
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    
    
        
        
    public boolean deleteAbonoLoteByManzana(Manzana manzana, User user){
        logger.info("addLote");
        
        boolean success = false;

        Transaction transaction = null;
        
        try{
            
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            int update = session.createQuery("UPDATE AbonoLote " 
                    + "SET estatusActivo = :estatusActivo, " 
                    + " lastUpdatedBy = :user, " 
                    + " lastUpdatedOn = :date " 
                    
                    + "WHERE lote IN (SELECT id FROM Lote WHERE manzana= :manzana)")
                    .setParameter("user", user)
                    .setParameter("date",new Date())
                    .setParameter("estatusActivo",GenericEnumType.DISABLED)
                    .setParameter("manzana",manzana)
                    .executeUpdate();

            transaction.commit();
            
            
           if(update > 0) success = true;
        
        
        
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }    
    
    
    public boolean deleteManzanaByPredio(Predio predio, User user){
        logger.info("addLote");
        
        boolean success = false;

        Transaction transaction = null;
        
        try{
            
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            int update = session.createQuery("UPDATE Manzana "
                    + "SET estatusActivo = :estatusActivo, "
                    + " lastUpdatedBy = :user, "
                    + " lastUpdatedOn = :date "
                    
                    + "WHERE  predio = :predio")
                    .setParameter("user", user)
                    .setParameter("date",new Date())
                    .setParameter("estatusActivo",GenericEnumType.DISABLED)
                    .setParameter("predio",predio)
                    .executeUpdate();

            transaction.commit();
            
            
           if(update > 0) success = true;
        
        
        
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean deleteAbonoProyectoByPredio(Predio predio, User user){
        logger.info("addLote");
        
        boolean success = false;

        Transaction transaction = null;
        
        try{
            
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            int update = session.createQuery("UPDATE AbonoProyecto "
                    + "SET estatusActivo = :estatusActivo, "
                    + " lastUpdatedBy = :user, "
                    + " lastUpdatedOn = :date "
                    
                    + "WHERE  predio = :predio")
                    .setParameter("user", user)
                    .setParameter("date",new Date())
                    .setParameter("estatusActivo",GenericEnumType.DISABLED)
                    .setParameter("predio",predio)
                    .executeUpdate();

            transaction.commit();
            
            
           if(update > 0) success = true;
        
        
        
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    
    public boolean deleteLoteByPredio(Predio predio, User user){
        logger.info("addLote");
        
        boolean success = false;

        Transaction transaction = null;
        
        try{
            
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            int update = session.createQuery("UPDATE Lote "
                    + "SET estatusActivo = :estatusActivo, "
                    + " lastUpdatedBy = :user, "
                    + " lastUpdatedOn = :date "
                    
                    + "WHERE  manzana in (SELECT id FROM Manzana WHERE predio = :predio)")
                    .setParameter("user", user)
                    .setParameter("date",new Date())
                    .setParameter("estatusActivo",GenericEnumType.DISABLED)
                    .setParameter("predio",predio)
                    .executeUpdate();

            transaction.commit();
            
            
           if(update > 0) success = true;
        
        
        
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    
    public boolean deleteAbonoLoteByPredio(Predio predio, User user){
        logger.info("addLote");
        
        boolean success = false;

        Transaction transaction = null;
        
        try{
            
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            int update = session.createQuery("UPDATE AbonoLote "
                    + "SET estatusActivo = :estatusActivo, "
                    + " lastUpdatedBy = :user, "
                    + " lastUpdatedOn = :date "
                    
                    + "WHERE lote in ( SELECT id FROM Lote WHERE manzana in (SELECT id FROM Manzana WHERE predio = :predio))")
                    .setParameter("user", user)
                    .setParameter("date",new Date())
                    .setParameter("estatusActivo",GenericEnumType.DISABLED)
                    .setParameter("predio",predio)
                    .executeUpdate();

            transaction.commit();
            
            
           if(update > 0) success = true;
        
        
        
        } catch (HibernateException e) {
            logger.error("Person can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addPerson() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    
    
    

    public boolean addAbonoProyecto(AbonoProyecto abono, User user, boolean save) {
        logger.info("addAbonoProyecto");

        boolean success = false;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            if (save) {
                abono.setCreatedBy(user);
                abono.setCreatedOn(new Date());
                session.save(abono);
                transaction.commit();

                logger.info("AbonoProyecto " + abono.getId());
            } else {
                abono.setLastUpdatedBy(user);
                abono.setLastUpdatedOn(new Date());
                session.update(abono);
                transaction.commit();
                logger.info("AbonoProyecto updated " + abono.getId());
            }

            success = true;
        } catch (HibernateException e) {
            logger.error("Abono can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addAbonoProyecto() ", e);
            rollback(transaction);
        }
        return success;
    }

    public boolean contarAbonos(Predio predio) {
        boolean success = true;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
            Root<AbonoProyecto> root = criteria.from(AbonoProyecto.class);
            criteria.select(builder.count(root));
            
            
            Predicate predioPredicate = builder.equal(root.get("predio"), predio);
            Predicate tipoPredicate = builder.equal(root.get("tipoAbono"), TipoAbono.ABONO);
            
            criteria.where(builder.and(predioPredicate,tipoPredicate));
            
           
            Long conteo = session.createQuery(criteria).getSingleResult();
            

          
            transaction.commit();
            if (conteo > 0) {
                success = false;
            }

        } catch (HibernateException e) {
            logger.error("Abono can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addAbonoProyecto() ", e);
            rollback(transaction);
        }

        return success;

    }
    
       public List<AbonoProyecto> buscarAbonosProyectos(Location location) {
        logger.info("buscarAbonosProyectos..");

        List<AbonoProyecto> result = null;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<AbonoProyecto> criteria = builder.createQuery(AbonoProyecto.class);
            Root<AbonoProyecto> root = criteria.from(AbonoProyecto.class);
            Predicate criterioLocation = builder.equal(root.get("predio").get("location"), location);
            criteria.where(builder.and(criterioLocation));          
            criteria.orderBy(builder.asc(root.get("fechaAPagar")));
            
            result = session.createQuery(criteria).getResultList();

            logger.info("Total of predios found: " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Unable to load predios list ", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method fillAllPredio", e);
        }

        return result;
    }
    
     public List<AbonoProyecto> fillAllAbonoProyecto(Predio predio) {
        logger.info("Searching all abonoProyecto..");

        List<AbonoProyecto> result = null;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<AbonoProyecto> criteria = builder.createQuery(AbonoProyecto.class);
            Root<AbonoProyecto> root = criteria.from(AbonoProyecto.class);

            Predicate predioPredicate = builder.equal(root.get("predio"), predio);
            
            
            criteria.where(builder.and(predioPredicate));
            
            criteria.orderBy(builder.asc(root.get("fechaAPagar")));
            
            result = session.createQuery(criteria).getResultList();

            logger.info("Total of predios found: " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Unable to load predios list ", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method fillAllPredio", e);
        }

        return result;
    }
     
     
      public boolean contarLotesVendidosApartados(Manzana apple) {
        logger.info("Searching all lotes..");

        boolean success = true;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
            Root<Lote> root = criteria.from(Lote.class);
            criteria.select(builder.count(root));

            Predicate criterio=(builder.equal(root.get("manzana"), apple));
            Predicate criterioActivo=builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);
            Predicate vendidos = builder.equal(root.get("estatusLote"), EstatusLote.VENDIDO);
            Predicate apartados = builder.equal(root.get("estatusLote"), EstatusLote.APARTADO);
            
            Predicate vendidosOApartados =builder.or(vendidos,apartados);
            criteria.where(builder.and(criterio,criterioActivo,vendidosOApartados));
            Long conteo = session.createQuery(criteria).getSingleResult();
            

          
            transaction.commit();
            if (conteo > 0) {
                success = false;
            }
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Unable to load lotes list ", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method fillAllLotes", e);
        }

        return success;
    }
     
     public List<Predio> fillPredioDatatableByCustomer(String propietario) {

    Transaction transaction = null;
    List<Predio> result = null;

    try {
        logger.info("Searching all Predio..");
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        transaction = session.beginTransaction();
        CriteriaBuilder builder = session.getCriteriaBuilder();

        CriteriaQuery<Predio> criteria = builder.createQuery(Predio.class);
        Root<Predio> root = criteria.from(Predio.class);

        criteria.where(builder.and(builder.equal(root.get("propetiario").get("id"), propietario),builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED)));

        result = session.createQuery(criteria).getResultList();

        logger.info("Total of Predio found: " + (null == result ? -1 : result.size()));
        transaction.commit();
    } catch (HibernateException e) {
        logger.error("Can not load list of Predio", e);
        rollback(transaction);
    } catch (Exception e) {
        logger.error("Method fillPredioDatatable of location", e);
        rollback(transaction);
    }

    return result;
}
     
    public Predio fillPredioDatatableByid(String id) {

        Transaction transaction = null;
        Predio result = null;

        try {
            logger.info("Searching Predio..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<Predio> criteria = builder.createQuery(Predio.class);
            Root<Predio> root = criteria.from(Predio.class);

            criteria.where(builder.and(builder.equal(root.get("id"), id)));

            result = session.createQuery(criteria).getSingleResult();

            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load  Predio", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillPredioDatatableByid", e);
            rollback(transaction);
        }

        return result;
    }
    
    public proyectosLotesView getProyectoLotes(String idProyecto){
    
     Transaction transaction = null;
        proyectosLotesView result = null;

        try {
            logger.info("Searching Predio..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<proyectosLotesView> criteria = builder.createQuery(proyectosLotesView.class);
            Root<proyectosLotesView> root = criteria.from(proyectosLotesView.class);

            criteria.where(builder.and(builder.equal(root.get("id"), idProyecto)));

            result = session.createQuery(criteria).getSingleResult();

            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load  Predio", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillPredioDatatableByid", e);
            rollback(transaction);
        }

        return result;
    }
    
    public Double getTotalUrbanizacion (String idUrbanizacion) {
        logger.info("existIncompleteBefore");
        
        Transaction transaction = null;
        Double count = 0D;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            
            count = (Double) session.createQuery("SELECT sum(saldoPagado) from DetalleLoteUrbanizacion WHERE urbanizacion.id = :idUrbanizacion").setParameter("idUrbanizacion", idUrbanizacion)
            .getSingleResult();
   
            
           
            logger.info("Total of abonos found: " + count);
            transaction.commit();
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Unable to count abonos", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method countPagosByLote", e);
        }
        return count;
    }


}
