/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.taxiservicios.controller.admin;

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.admin.Bitacora;
import com.arrebol.taxiservicios.model.catalog.Location;
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.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 Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
public class BitacoraController extends ConnectionManager implements Serializable {

    /**
     * Find bitacora list between Dates (Start date and End Date).
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public List<Bitacora> findBitacoraListBetweenDates(Date startDate, Date endDate, String idLocation) {
        logger.info("findBitacoraListBetweenDates");

        List<Bitacora> results = null;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Bitacora> query = builder.createQuery(Bitacora.class);
            Root<Bitacora> root = query.from(Bitacora.class);

            Path<String> id = root.get("id");
            Path<String> commentsUser = root.get("commentsUser");
            Path<String> action = root.get("action");
            Path<String> description = root.get("description");
            Path<String> nameUser = root.get("nameUser");
            Path<Date> createdOn = root.get("createdOn");

            Predicate startDatePredicate = builder.greaterThanOrEqualTo(root.get("createdOn"), startDate);
            Predicate endDatePredicate = builder.lessThanOrEqualTo(root.get("createdOn"), endDate);
            Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation));

            query.select(
                    builder.construct(
                            Bitacora.class, id, commentsUser,
                            action, description, nameUser, createdOn
                    )
            );
            query.where(builder.and(startDatePredicate, endDatePredicate, locationPredicate));
            query.orderBy(builder.asc(root.get("createdOn")));

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

            transaction.commit();

            logger.info("Bitacora list " + results.size());
        } catch (HibernateException e) {
            logger.error("Can not find bitacora list between dates", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findBitacoraListBetweenDates()", e);
            rollback(transaction);
        }
        return results;
    }

    /**
     *
     * @param bitacora
     * @return
     */
    public boolean saveNewRecordInBitacora(Bitacora bitacora, String idLocation) {
        boolean success = false;
        Transaction transaction = null;

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

            bitacora.setLocation(new Location(idLocation));
            session.save(bitacora);
            transaction.commit();

            success = true;

            logger.info("New record was inserted in bitacora");
        } catch (HibernateException e) {
            logger.error("Can not insert a bitacora event", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method saveNewRecordInBitacora()", e);
            rollback(transaction);
        }
        return success;
    }

    final Logger logger = LogManager.getLogger(BitacoraController.class);
    private static final long serialVersionUID = -6732331411572526429L;

}
