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

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.queries.PersonNQ;
import com.arrebol.taxiservicios.controller.util.DateWrapper;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.admin.Sale;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.catalog.Holiday;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.dashboard.ToCollect;
import com.arrebol.taxiservicios.model.enums.GenericEnumType;
import com.arrebol.taxiservicios.model.enums.PersonType;
import com.arrebol.taxiservicios.model.enums.PlatformType;
import com.arrebol.taxiservicios.model.stocktaking.view.HistoryUpdateKm;
import com.arrebol.taxiservicios.model.view.dashboard.DashboardToCollectView;
import com.arrebol.taxiservicios.model.view.dashboard.InsuranceDashboardListView;
import com.arrebol.taxiservicios.model.view.dashboard.PersonSearchByActiveAndBlackListView;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
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 DashboardController extends ConnectionManager implements Serializable {

    public boolean updateInsuranceInformation(String seguro, String cobertura,
            Date fecha, String id) {
        logger.info("updateInsuranceInformation");

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

            /**
             * Taxi Servicios goes for user details.
             */
            CriteriaBuilder builder = session.getCriteriaBuilder();

            builder = session.getCriteriaBuilder();
            CriteriaUpdate<Taxi> update = builder.createCriteriaUpdate(Taxi.class);
            Root<Taxi> rootPerson = update.from(Taxi.class);

            update.set("insuranceName", seguro);
            update.set("insuranceCobertura", cobertura);
            update.set("insuranceEndDate", fecha);

            update.where(builder.equal(rootPerson.get("id"), id));

            int total = session.createQuery(update).executeUpdate();

            if (1 == total) {
                logger.info("Taxi updated taxi_id: " + id);
                transaction.commit();

                success = true;
            } else {
                logger.error("Taxi can not be updated " + id);
                transaction.rollback();
            }
        } catch (HibernateException e) {
            logger.error("Taxi cannot be updated " + id, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updateInsuranceInformation(" + id + ") ", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean updateKilometrajeInformation(double Kilometraje, String id) {
        logger.info("updateKilometrajeInformation");

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

            /**
             * Taxi Servicios goes for user details.
             */
            CriteriaBuilder builder = session.getCriteriaBuilder();

            builder = session.getCriteriaBuilder();
            CriteriaUpdate<Taxi> update = builder.createCriteriaUpdate(Taxi.class);
            Root<Taxi> rootPerson = update.from(Taxi.class);

            update.set("km", (float) Kilometraje);

            update.where(builder.equal(rootPerson.get("id"), id));

            int total = session.createQuery(update).executeUpdate();

            if (1 == total) {
                logger.info("Taxi updated taxi_id: " + id);
                transaction.commit();

                success = true;
            } else {
                logger.error("Taxi can not be updated " + id);
                transaction.rollback();
            }
        } catch (HibernateException e) {
            logger.error("Taxi cannot be updated " + id, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updateKilometrajeInformation(" + id + ") ", e);
            rollback(transaction);
        }
        return success;
    }
    
    public Taxi getTaxiObject(String driverId) {
        logger.info("getTaxiObject");
        //String idTaxi = getTaxiByDriver(driverId);
        Taxi taxi = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            taxi = session.find(Taxi.class, driverId);
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Sale can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addSale() ", e);
            rollback(transaction);
        }
        return taxi;
    }
    
    public boolean saveHistoryUpdateKm(HistoryUpdateKm historyUpdateKm) {
        logger.info("saveHistoryUpdateKm");

        boolean success = false;
        Transaction transaction = null;

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

            session.save(historyUpdateKm);
            logger.info("historyUpdateKm saved " + historyUpdateKm.getId());
            transaction.commit();

            success = true;
        } catch (HibernateException e) {
            logger.error("historyUpdateKm can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method saveHistoryUpdateKm() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    public String getTaxiByDriver(String driverId) {

        Transaction transaction = null;
        String result = null;

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

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

            Path<String> idPath = root.get("id");

            criteria.select(
                    builder.construct(Taxi.class, idPath
                    ));

            criteria.where(builder.equal(root.get("driver"), new Person(driverId)));

            result = session.createQuery(criteria).uniqueResult().getId();
            transaction.commit();
            logger.info("Taxi found");
        } catch (HibernateException e) {
            logger.error("Can not load the taxi by driver ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getTaxiByDriver of Sale", e);
            rollback(transaction);
        }

        return result;
    }
    
    /**
     *
     * @return
     */
    public List<Taxi> getAllTaxiWithInsuranceEndDateToFinish() {
        logger.info("Searching all getAllTaxiWithInsuranceEnDateToFinish");

        List<Taxi> result = null;
        Transaction transaction = null;
        try {
            Calendar date = Calendar.getInstance();
            date.add(Calendar.HOUR, -6);
            date.add(Calendar.DAY_OF_YEAR, 10);

            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Taxi> criteria = builder.createQuery(Taxi.class);

            Root<Taxi> root = criteria.from(Taxi.class);

            Path<String> economicNumber = root.get("economicNumber");
            Path<Date> insuranceEndDate = root.get("insuranceEndDate");
            Path<Date> insuranceName = root.get("insuranceName");
            Path<Date> insuranceCobertura = root.get("insuranceCobertura");
            Path<Person> driver = root.get("driver");
            Path<Person> customer = root.get("customer");

            criteria.select(builder.construct(Taxi.class, economicNumber, insuranceEndDate, driver, customer, insuranceName, insuranceCobertura));

            Predicate lastTenDays = builder.lessThanOrEqualTo(root.get("insuranceEndDate"), date.getTime());

            criteria.where((builder.equal(root.get("active"), Boolean.TRUE)));
            criteria.orderBy(builder.asc(root.get("insuranceEndDate")));

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

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

        return result;
    }

    /**
     *
     * @return
     */
    public List<InsuranceDashboardListView> getInsuranceDashboardListView() {
        List<InsuranceDashboardListView> results = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            results = session.createQuery("FROM InsuranceDashboardListView")
                    .getResultList();
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load list of insurance taxis detials ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getInsuranceDashboardListView", e);
            rollback(transaction);
        }

        return results;
    }

    /**
     *
     * @return
     */
    public List<Person> getAllDriverLicenseEndDateToFinish(Location location) {
        logger.info("Searching all getAllDriverLicenseEndDateToFinish");

        List<Person> result = null;
        Transaction transaction = null;
        try {
            Calendar date = Calendar.getInstance();
            date.add(Calendar.HOUR, -6);
            date.add(Calendar.DAY_OF_YEAR, 10);

            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<Date> insuranceEndDate = root.get("expirationLicenseDate");
            Path<String> firstName = root.get("firstName");
            Path<String> secondName = root.get("secondName");
            Path<String> lastName = root.get("lastName");
            Path<String> middleName = root.get("middleName");

            criteria.select(builder.construct(Person.class, insuranceEndDate,
                    firstName, secondName, lastName, middleName));

            Predicate lastTenDays = builder.lessThanOrEqualTo(root.get("expirationLicenseDate"), date.getTime());

            criteria.where(lastTenDays, builder.and(
                    builder.equal(root.get("personType"), PersonType.DRIVER),
                    builder.equal(root.get("location"),location),
                    builder.equal(root.get("active"), true)
            ));

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

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

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

        return result;
    }

    /**
     *
     * @return
     */
    public List<Person> getAllBirthDayPerson() {
        logger.info("Searching all getAllBirthDayPerson");

        List<Person> result = null;
        Transaction transaction = null;
        try {
            Calendar date = Calendar.getInstance();
            date.add(Calendar.HOUR, -6);
            date.add(Calendar.DAY_OF_YEAR, 10);

            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> firstName = root.get("firstName");
            Path<String> secondName = root.get("secondName");
            Path<String> lastName = root.get("lastName");
            Path<String> middleName = root.get("middleName");
            Path<Date> birthdate = root.get("birthdate");
            Path<Date> admissionDate = root.get("admissionDate");
            Path<PersonType> personType = root.get("personType");

            criteria.select(builder.construct(Person.class, firstName, secondName,
                    lastName, middleName, birthdate, admissionDate, personType));

            criteria.where(builder.equal(root.get("active"), true));

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

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

        return result;
    }

    /**
     * Get all metrics total of payDay, paySaving, accident and total of totals.
     *
     * @return Array with 4 position if exist Sale in current day otherwise
     * false.
     */
    public Object getSaleMetrics() {
        logger.info("getSaleMetrics");

        Object result = null;
        Transaction transaction = null;
        try {
            Calendar c = Calendar.getInstance();

            c.add(Calendar.HOUR, -6);

            String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH);

            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            String query = "select sum(payDay), sum(paySaving), sum(accident), "
                    + "sum(payDay) + sum(paySaving) + sum(accident)"
                    + "from Sale where DATE(payDate) = '" + date + "'";

            result = session.createQuery(query).uniqueResult();

            transaction.commit();
            logger.info("Metrics loaded");
        } catch (HibernateException e) {
            logger.error("Can not load the sale metrics ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getSaleMetrics", e);
            rollback(transaction);
        }
        return result;
    }

    /**
     * Get totoal of active drivers in system query:<br/>
     * select count(id) from Person where personType = 'DRIVER' and active =
     * true
     *
     * @return Array with 1 position of the total of active drivers in system.
     */
    public Object getTotalDrivers() {
        logger.info("getTotalDrivers");

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

            String query = "select count(id) from Person where personType = 'DRIVER' and active = 1";

            result = session.createQuery(query).uniqueResult();

            transaction.commit();
            logger.info("Total of drivers result");
        } catch (HibernateException e) {
            logger.error("Can not load the sale metrics ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getSaleMetrics", e);
            rollback(transaction);
        }
        return result;
    }

    /**
     *
     * @return
     */
    public List<Sale> getAllSalesByDriver() {
        logger.info("getAllSalesByDriver");

        List<Sale> sales = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Sale> criteria = builder.createQuery(Sale.class);

            Root<Sale> root = criteria.from(Sale.class);

            Path<Person> person = root.get("person");
            Path<Date> payDate = root.get("payDate");

            Predicate starDate = builder.greaterThanOrEqualTo(root.get("payDate"), DateWrapper.today().subtractHours(6).subtractMonths(1).firstDateForMonth().midnigthTime().asDate());
            Predicate endDate = builder.lessThan(root.get("payDate"), DateWrapper.today().subtractHours(6).add(Calendar.HOUR, 24).midnigthTime().asDate());

            criteria.select(builder.construct(Sale.class, payDate, person));
            criteria.where(builder.and(starDate, endDate));

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

            transaction.commit();
            logger.info("Total of sales " + sales.size());
        } catch (HibernateException e) {
            logger.error("Can not load the all sales ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getAllSalesByDriver()", e);
            rollback(transaction);
        }

        return sales;
    }

    /**
     *
     * @return
     */
    public List<Holiday> getAllHolidays() {
        logger.info("getAllHolidays");

        List<Holiday> holidays = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Holiday> criteria = builder.createQuery(Holiday.class);

            Root<Holiday> root = criteria.from(Holiday.class);

            Path<String> description = root.get("description");
            Path<Date> holiday = root.get("holiday");

            Predicate starDate = builder.greaterThanOrEqualTo(root.get("holiday"), DateWrapper.today().subtractHours(6).subtractMonths(1).firstDateForMonth().midnigthTime().asDate());
            Predicate endDate = builder.lessThan(root.get("holiday"), DateWrapper.today().subtractHours(6).add(Calendar.HOUR, 24).midnigthTime().asDate());

            criteria.select(builder.construct(Holiday.class, holiday, description));
            criteria.where(builder.and(starDate, endDate));

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

            transaction.commit();
            logger.info("Total of holidays " + holidays.size());
        } catch (HibernateException e) {
            logger.error("Can not load the holiday ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getAllHolidays()", e);
            rollback(transaction);
        }

        return holidays;
    }

    /**
     *
     * @return
     */
    public List<Person> getAllActiveDrivers() {
        logger.info("Start getAllActiveDrivers");

        Transaction transaction = null;
        List<Person> drivers = 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");

            criteria.select(builder.construct(Person.class, idPath));

            criteria.where(
                    builder.and(
                            builder.equal(root.get("active"), true),
                            builder.equal(root.get("personType"), PersonType.DRIVER)
                    )
            );

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

            transaction.commit();
            logger.info("Drivers succefully loaded, size: " + drivers.size());
        } catch (HibernateException e) {
            logger.error("Drivers can not be loaded ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getAllActiveDrivers()", e);
            rollback(transaction);
        }
        return drivers;
    }

    /**
     *
     * @return
     */
    public List<ToCollect> getCollectByRange() {
        logger.info("getCollectByRange");

        List<ToCollect> collects = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<ToCollect> criteria = builder.createQuery(ToCollect.class);

            Root<ToCollect> root = criteria.from(ToCollect.class);

            Predicate starDate = builder.greaterThanOrEqualTo(root.get("collect"), DateWrapper.today().subtractHours(6).subtractMonths(1).firstDateForMonth().midnigthTime().asDate());
            Predicate endDate = builder.lessThan(root.get("collect"), DateWrapper.today().subtractHours(6).add(Calendar.HOUR, 24).midnigthTime().asDate());

            criteria.select(root);
            criteria.where(builder.and(starDate, endDate));

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

            transaction.commit();
            logger.info("Total of collects " + collects.size());
        } catch (HibernateException e) {
            logger.error("Can not load the collect days ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getCollectByRange()", e);
            rollback(transaction);
        }

        return collects;
    }

    /**
     *
     * @return
     */
    public List<Object> countCollectByRange() {
        logger.info("countCollectByRange");

        List<Object> collects = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            StringBuilder sb = new StringBuilder("select count(tc.total), tc.driver, tx.economicNumber from ToCollect tc");

            sb.append(" inner join Person prs on tc.driver = prs.id");
            sb.append(" inner join Taxi tx on prs.id = tx.driver");
            sb.append(" where tc.collect >= '");
            sb.append(format.format(DateWrapper.today().subtractHours(6).subtractMonths(1).firstDateForMonth().midnigthTime().asDate()));
            sb.append("' and tc.collect < '");
            sb.append(format.format(DateWrapper.today().subtractHours(6).add(Calendar.HOUR, 24).midnigthTime().asDate()));
            sb.append("' group by tc.driver, tx.economicNumber order by 1 desc");

            logger.info("Query = " + sb.toString());

            collects = session.createQuery(sb.toString()).getResultList();

            transaction.commit();
            logger.info("Total of count collects " + collects.size());
        } catch (HibernateException e) {
            logger.error("Can not load the count collect days ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method countCollectByRange()", e);
            rollback(transaction);
        }

        return collects;
    }

    /**
     * Load persons to show in dashboard birthdate and anniversaries.
     *
     * @param numberOfQuery If 1 eq findAllBirthdateInADate.<br/>If 2 eq
     * findAllDriversByAnniversaryInADate.<br/>If 3 eq
     * findAllDriversBySixMonthInADate.
     * @param startDate
     * @param endDate
     * @return
     */
    public List<Person> findAllInADate(int numberOfQuery, Date startDate, Date endDate) {
        logger.info("findAllInADate (numberOfQuery: " + numberOfQuery + ")");
        logger.info("startDate: " + startDate);
        logger.info("endDate: " + endDate);

        List<Person> personLst = new ArrayList<>();
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            String query;

            switch (numberOfQuery) {
                case 1:
                    query = PersonNQ.QUERY_FIND_ALL_BIRTHDATE_IN_A_DATE;
                    break;
                case 2:
                    query = PersonNQ.QUERY_FIND_ALL_DRIVERS_BY_ANNIVERSARY_IN_A_DATE;
                    break;
                case 3:
                    query = PersonNQ.QUERY_FIND_ALL_DRIVERS_BY_SIX_MONTH_IN_A_DATE;
                    break;
                default:
                    query = PersonNQ.QUERY_FIND_ALL_DRIVERS_BY_ANNIVERSARY_IN_A_DATE;
                    break;
            }

            List<Object[]> addressObjArray = session.getNamedQuery(query)
                    .setParameter(PersonNQ.PARAM_START_DATE, startDate)
                    .setParameter(PersonNQ.PARAM_END_DATE, endDate)
                    .getResultList();

            switch (numberOfQuery) {
                case 1:
                    addressObjArray.stream().map((row) -> new Person((String) row[1], (Date) row[0], (PersonType.valueOf((String) row[2])))).forEachOrdered((person) -> {
                        personLst.add(person);
                    });
                    break;
                default:
                    addressObjArray.stream().map((row) -> new Person((String) row[1], (PersonType.valueOf((String) row[2])), (Date) row[0])).forEachOrdered((person) -> {
                        personLst.add(person);
                    });
                    break;
            }

            transaction.commit();
            logger.info("Total of records in list: " + personLst.size());
        } catch (HibernateException e) {
            logger.error("Can not load persons ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findAllInADate()", e);
            rollback(transaction);
        }

        return personLst;
    }

    /**
     *
     * @return
     */
    public List<DashboardToCollectView> findAllDashboardToCollectView() {
        logger.info("Searching all findAllDashboardToCollectView");

        List<DashboardToCollectView> result = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<DashboardToCollectView> criteria = builder.createQuery(DashboardToCollectView.class);

            Root<DashboardToCollectView> root = criteria.from(DashboardToCollectView.class);

            Path<String> idTaxi = root.get("idTaxi");
            Path<String> economicNumber = root.get("economicNumber");
            Path<String> modelVehicle = root.get("modelVehicle");
            Path<String> idDriver = root.get("idDriver");
            Path<String> driverName = root.get("driverName");
            Path<PlatformType> platform = root.get("platform");
            Path<Double> payDay = root.get("payDay");
            Path<Double> paySaving = root.get("paySaving");
            Path<Double> payAccident = root.get("payAccident");
            Path<Double> totalToPay = root.get("totalToPay");
            Path<Double> amountPaid = root.get("amountPaid");
            Path<Float> totalAdeudo = root.get("totalAdeudo");

            criteria.select(builder.construct(DashboardToCollectView.class, idTaxi,
                    economicNumber, modelVehicle, idDriver, driverName, platform,
                    payDay, paySaving, payAccident, totalToPay, amountPaid, totalAdeudo)
            );
            criteria.orderBy(builder.asc(root.get("driverName")));

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

            logger.info("Total of Dashboard To Collect View found : " + (null == result ? 0 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load list of Dashboard To Collect View", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findAllDashboardToCollectView", e);
            rollback(transaction);
        }

        return result;
    }

    /**
     *
     * @param like
     * @return
     */
    public List<String> findPersonInBlackListByName(String like) {
        logger.info("findPersonInBlackListByName");

        List<String> results = new ArrayList<>();
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<String> query = builder.createQuery(String.class);
            Root<PersonSearchByActiveAndBlackListView> root = query.from(PersonSearchByActiveAndBlackListView.class);

            query.select(root.get("blackListDescription"));
            query.where(
                    builder.like(root.get("name"), "%" + like + "%"),
                    builder.and(
                            builder.equal(root.get("active"), false),
                            builder.equal(root.get("blackList"), GenericEnumType.ENABLED)
                    )
            );

            results = session.createQuery(query).getResultList();

            transaction.commit();
            logger.info("Coincidences " + results);
        } catch (HibernateException e) {
            logger.error("Can not load black list", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findPersonInBlackListByName", e);
            rollback(transaction);
        }
        return results;
    }

    private static final long serialVersionUID = 5688595456684273345L;

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

}
