/*
 * 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.juridicas;

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
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.juridicas.DetalleLoteEtapa;
import com.arrebol.taxiservicios.model.predio.Lote;
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.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 DetalleLoteEtapaController extends ConnectionManager implements Serializable {

    private static final long serialVersionUID = -559465932081273592L;

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

    public Long contarLoteEtapabyLote(Lote lote, Location location) {
        logger.info("contarLoteEtapa");
        Long conteo = 0L;

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

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
            Root<DetalleLoteEtapa> root = criteria.from(DetalleLoteEtapa.class);
            criteria.select(builder.count(root));
            
            Predicate criterioActivo = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);  
            Predicate criterio = builder.equal(root.get("lote"), lote);
            Predicate criterioLocation = builder.equal(root.get("lote").get("manzana").get("predio").get("location"), location);
            criteria.where(builder.and(criterio,criterioLocation,criterioActivo));

            conteo = session.createQuery(criteria).getSingleResult();
            transaction.commit();

            logger.info("LoteEtapa encontrados " + conteo);

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

        return conteo;

    }

    public boolean addDetalleLoteEtapa(DetalleLoteEtapa detalleLoteEtapa, User user) {
        logger.info("addDetalleLoteEtapa");

        boolean success = false;

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

            if (detalleLoteEtapa.getId() == null) {
                detalleLoteEtapa.setId(UUID.randomUUID().toString());
                detalleLoteEtapa.setCreatedBy(user);
                detalleLoteEtapa.setCreatedOn(new Date());
                session.save(detalleLoteEtapa);
                transaction.commit();
                logger.info("DetalleLoteEtapa saved " + detalleLoteEtapa.getId());
            } else {
                detalleLoteEtapa.setLastUpdatedBy(user);
                detalleLoteEtapa.setLastUpdatedOn(new Date());
                session.update(detalleLoteEtapa);
                transaction.commit();
                logger.info("DetalleLoteEtapa updated " + detalleLoteEtapa.getId());
            }

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

    public List<DetalleLoteEtapa> fillDetalleLoteEtapaDatatable(Location location) {

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

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

            CriteriaQuery<DetalleLoteEtapa> criteria = builder.createQuery(DetalleLoteEtapa.class);
            Root<DetalleLoteEtapa> root = criteria.from(DetalleLoteEtapa.class);
            
            Predicate criterioActivo = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);   
            Predicate criterioPredioLocation = builder.equal(root.get("lote").get("manzana").get("predio").get("location"), location);
            criteria.where(builder.and(criterioPredioLocation, criterioActivo));

            criteria.orderBy(builder.asc(root.get("createdOn")));

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

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

        return result;
    }
    
    public List<DetalleLoteEtapa> fillDetalleLoteEtapaByLote(Lote lote) {

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

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

            CriteriaQuery<DetalleLoteEtapa> criteria = builder.createQuery(DetalleLoteEtapa.class);
            Root<DetalleLoteEtapa> root = criteria.from(DetalleLoteEtapa.class);
            
            Predicate criterioActivo = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);   
            Predicate criterioLote = (builder.equal(root.get("lote"), lote));
            criteria.where(builder.and(criterioLote, criterioActivo));
            criteria.orderBy(builder.desc(root.get("createdOn")));
          
            result = session.createQuery(criteria).getResultList();

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

        return result;
    }
}
