/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.arrebol.taxiservicios.controller.predio;

import com.arrebol.taxiservicios.controller.admin.GenericPersonController;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.GenericEnumType;
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.Urbanizacion;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
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 Usuario
 */
public class DetalleLoteUrbanizacionController extends GenericPersonController implements Serializable {

    private static final long serialVersionUID = -6265444716269535946L;

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

    public boolean addDetalleLoteUrbanizacion(DetalleLoteUrbanizacion detalleLoteUrbanizacion, User user) {
        logger.info("addDetalleLoteUrbanizacion");

        boolean success = false;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            detalleLoteUrbanizacion.setId(UUID.randomUUID().toString());
            detalleLoteUrbanizacion.setCreatedBy(user);
            detalleLoteUrbanizacion.setCreatedOn(new Date());
            session.save(detalleLoteUrbanizacion);
            transaction.commit();

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

    public List<DetalleLoteUrbanizacion> buscarDetallesLotesPorLotes(String idLote, String idUrbanizacion) {
        Transaction transaction = null;
        List<DetalleLoteUrbanizacion> result = null;

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

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

            Predicate criterioLote = builder.equal(root.get("lote").get("id"), idLote);
            Predicate criterioUrbanzacion = builder.equal(root.get("urbanizacion").get("id"), idUrbanizacion);
            criteria.where(builder.and(criterioLote, criterioUrbanzacion));

            Order order = builder.desc(root.get("createdOn"));
            criteria.orderBy(order);

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

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

        return result;
    }
    
     public List<DetalleLoteUrbanizacion> buscarDetallesLotesBetweenDates(String id, String type, Date startDate, Date endDate) {
        Transaction transaction = null;
        List<DetalleLoteUrbanizacion> result = null;

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

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

            Predicate criterio = null; 
                    
            switch (type) {
                case "proyecto":
                    criterio = builder.equal(root.get("lote").get("manzana").get("predio").get("id"), id);
                    break;
                case "manzana":
                    criterio = builder.equal(root.get("lote").get("manzana").get("id"), id);
                    break;
                case "lote":
                    criterio = builder.equal(root.get("lote").get("id"), id);
                    break;
                default:
                    break;
            }
            
            Predicate datesCriteria = builder.between(root.get("createdOn"), startDate, endDate);
            criteria.where(builder.and(criterio, datesCriteria));

            Order order = builder.desc(root.get("createdOn"));
            criteria.orderBy(order);

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

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

        return result;
    }
    
     public List<Predio> fillAllPredio(Location location) {
        logger.info("Searching all predios..");

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

        try {
            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);

            Path<String> id = root.get("id");
            Path<String> idPropetiario = root.get("propetiario");
            Path<String> nombreProyecto = root.get("nombreProyecto");
            Predicate criterioLocation = builder.equal(root.get("location"), location);
            Predicate criterioEstatus = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);
            criteria.select(builder.construct(Predio.class, id, idPropetiario, nombreProyecto));
            criteria.where(builder.and(criterioLocation, criterioEstatus));
            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<Manzana> fillAllManzanas(Predio predio) {
        logger.info("Searching all manzanas..");

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

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

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

            Predicate criterioActivo = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);
            Predicate criteriaPredio = builder.equal(root.get("predio"), predio);
            criteria.where(builder.and(criterioActivo, criteriaPredio));

            criteria.orderBy(builder.desc(root.get("nombre")));
            result = session.createQuery(criteria).getResultList();

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

        return result;
    }
    
    public List<Lote> fillAllLotes(Manzana manzana) {
        logger.info("Searching all lotes..");

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

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

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

            Predicate criterio = (builder.equal(root.get("manzana"), manzana));
            Predicate criterioActivo = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);
            criteria.where(builder.and(criterio, criterioActivo));
            result = session.createQuery(criteria).getResultList();

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

        return result;
    }
}
