/*
 * 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.EstatusSolicitud;
import com.arrebol.taxiservicios.model.enums.GenericEnumType;
import com.arrebol.taxiservicios.model.predio.Lote;
import com.arrebol.taxiservicios.model.predio.SolicitudTrasferenciaLote;
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.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 pc one
 */
public class CambiaLoteController extends GenericPersonController implements Serializable {

    private static final long serialVersionUID = -6265444716269535946L;

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

    public boolean addSolcitudTrasferencia(SolicitudTrasferenciaLote solicitud, User user, boolean save) {
        logger.info("addSolcitudTrasferencia");
        boolean success = false;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            if (save) {
                solicitud.setCreatedBy(user);
                solicitud.setCreatedOn(new Date());
                session.save(solicitud);
                transaction.commit();
                logger.info("Solicitud saved " + solicitud.getId());
            } else {
                solicitud.setLastUpdatedBy(user);
                solicitud.setLastUpdatedOn(new Date());
                session.update(solicitud);
                transaction.commit();
                logger.info("Solicitud updated " + solicitud.getId());
            }
            success = true;
        } catch (HibernateException e) {
            logger.error("Solicitud can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addSolcitudTrasferencia() ", e);
            rollback(transaction);
        }
        return success;
    }

    public List<SolicitudTrasferenciaLote> fillAllSolicitudesTrasferenciaByLocation(Location location) {
        logger.info("Searching all solicitudes..");

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

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

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

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

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

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

        return result;
    }
    
        public List<SolicitudTrasferenciaLote> fillAllSolicitudesTrasferenciaByLote(Lote lote) {
        logger.info("Searching all solicitudes..");

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

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

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

            Predicate criterioActivo = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);
            Predicate criterioValLoteOrigen = builder.equal(root.get("loteOrigen"), lote);
            Predicate criterioValLoteDestino= builder.equal(root.get("loteDestino"), lote);
            criteria.where(builder.and(criterioActivo), builder.or(criterioValLoteOrigen, criterioValLoteDestino));

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

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

        return result;
    }

    public List<SolicitudTrasferenciaLote> fillSolicitudesTrasferenciaPendienteByLote(String idLote) {
        logger.info("Searching all solicitudes..");

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

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

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

            Predicate criterioActivo = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);
            Predicate criterioEstatusSolicitud = builder.equal(root.get("estatusSolicitud"), EstatusSolicitud.PENDIENTE);
            Predicate criterioL1 = builder.equal(root.get("loteOrigen").get("id"), idLote);
            Predicate criterioL2 = builder.equal(root.get("loteDestino").get("id"), idLote);
            criteria.where(builder.and(criterioActivo, criterioEstatusSolicitud), builder.or(criterioL1, criterioL2));

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

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

        return result;
    }
    
}
