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

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.catalog.LocationPaquetes;
import com.arrebol.taxiservicios.model.catalog.Paquetes;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.GenericEnumType;
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 pc one
 */
public class PaquetesController extends ConnectionManager implements Serializable {

   private static final long serialVersionUID = -6265444716269535946L;
   final Logger logger = LogManager.getLogger(getClass());

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

   public Paquetes findPaqueteById(String id) {
      Transaction transaction = null;
      Paquetes result = null;
      try {
         logger.info("Searching all Paquetes..");
         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         transaction = session.beginTransaction();
         CriteriaBuilder builder = session.getCriteriaBuilder();

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

         criteria.where(builder.equal(root.get("id"), id));
         result = session.createQuery(criteria).getSingleResult();

         logger.info("Paquete : " + result.getNombre());
         transaction.commit();
      } catch (HibernateException e) {
         logger.error("Could not find paquete ", e);
         rollback(transaction);
      } catch (Exception e) {
         logger.error("Method findPaqueteById", e);
         rollback(transaction);
      }
      return result;
   }

   public List<Paquetes> fillAllPaquetes() {
      Transaction transaction = null;
      List<Paquetes> result = null;
      try {
         logger.info("Searching all Paquetes..");
         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         transaction = session.beginTransaction();
         CriteriaBuilder builder = session.getCriteriaBuilder();

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

         criteria.where(builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED));
         criteria.orderBy(builder.asc(root.get("costo")));
         result = session.createQuery(criteria).getResultList();

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

   public List<Paquetes> fillAllPaquetesByMaximosLimites(int noLocasiones, int noUsuarios) {
      Transaction transaction = null;
      List<Paquetes> result = null;
      try {
         logger.info("Searching all Paquetes..");
         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         transaction = session.beginTransaction();
         CriteriaBuilder builder = session.getCriteriaBuilder();

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

         Predicate criterioActivo = builder.equal(root.get("estatusActivo"), GenericEnumType.ENABLED);
         Predicate criterioNoLo = builder.greaterThanOrEqualTo(root.get("numLocaciones"), noLocasiones);
         Predicate criterioNoUs = builder.greaterThanOrEqualTo(root.get("numeroUsuarios"), noUsuarios);
         Predicate criterioValDemo = builder.notEqual(root.get("id"), "f6277e17-d1a1-405b-ac40-4475c6ea8034");
         criteria.where(builder.and(criterioActivo, criterioNoLo, criterioNoUs, criterioValDemo));
         criteria.orderBy(builder.asc(root.get("costo")));

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

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

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

   public List<LocationPaquetes> fillAllLocationPaquetesByLocation(Location location) {
      Transaction transaction = null;
      List<LocationPaquetes> result = null;
      try {
         logger.info("Searching all Paquetes location..");
         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         transaction = session.beginTransaction();
         CriteriaBuilder builder = session.getCriteriaBuilder();

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

         criteria.where(builder.equal(root.get("location").get("id"), location.getId()));
         criteria.orderBy(builder.desc(root.get("createdOn")));
         result = session.createQuery(criteria).getResultList();

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

   public List<LocationPaquetes> fillAllLocationPaquetesByLocationAndEstatusActivo(Location location, GenericEnumType estatusActivo) {
      Transaction transaction = null;
      List<LocationPaquetes> result = null;
      try {
         logger.info("Searching all Paquetes location..");
         Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         transaction = session.beginTransaction();
         CriteriaBuilder builder = session.getCriteriaBuilder();

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

         Predicate criterio = (builder.equal(root.get("location").get("id"), location.getId()));
         Predicate criterio2 = (builder.equal(root.get("estatusActivo"), estatusActivo));
         criteria.where(builder.and(criterio, criterio2));
         criteria.orderBy(builder.asc(root.get("createdOn")));
         result = session.createQuery(criteria).getResultList();

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

}
