/*
 * 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.Taxi;
import com.arrebol.taxiservicios.model.admin.TiempoAire;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
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 Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
public class TiempoAireController extends ConnectionManager implements Serializable {

    /**
     * Find company's expenses by type (PAYMENT IN/OUT) and between start date
     * and end date.
     *
     * @param startDate
     * @param endDate
     * @param idLocation
     * @return List of all company expenses.
     */
    public List<TiempoAire> findBetweenDates(Date startDate, Date endDate, String idLocation) {
        logger.info("findBetweenDates");
        List<TiempoAire> results = new ArrayList<>();

        Transaction transaction = null;

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

            Path<String> id = root.get("id");
            Path<BigDecimal> amountMayoreo = root.get("amountMayoreo");
            Path<BigDecimal> amountMenudeo = root.get("amountMenudeo");
            Path<Taxi> taxi = root.get("taxi");
            Path<Date> vigencia = root.get("vigencia");
            Path<String> description = root.get("description");
            Path<Date> createdOn = root.get("createdOn");
            Path<User> createdByPath = root.get("createdBy");
            Path<Boolean> activeStatusPath = root.get("activeStatus");

            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(TiempoAire.class, id, amountMayoreo, amountMenudeo, description, taxi, vigencia, activeStatusPath, createdByPath, createdOn));
            query.where(builder.and(
                    startDatePredicate, endDatePredicate, locationPredicate
            ));
            query.orderBy(builder.asc(root.get("createdOn")));

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

            transaction.commit();

            logger.info("Tiempo aire's list " + results.size());
        } catch (HibernateException e) {
            logger.error("Can not load taxes list ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findBetweenDates() ", e);
            rollback(transaction);
        }
        return results;
    }

    /**
     * Update active status (ENEBLED/DISABLED) of Expense company ID.
     *
     * @param id
     * @param status
     * @param lastUpdatedBy
     * @return
     */
    public boolean updateStatus(String id, BasicType status, User lastUpdatedBy) {
        logger.info("updateStatus");

        boolean success = false;
        Transaction transaction = null;

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

            query.set(root.get("activeStatus"), status);
            query.set(root.get("lastUpdatedBy"), lastUpdatedBy);
            query.set(root.get("lastUpdatedOn"), new Date());

            query.where(builder.equal(root.get("id"), id));

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

            if (1 == total) {
                transaction.commit();
                success = true;
                logger.info("Update status successfully");
            } else {
                logger.info("CAN NOT update tiempo aire status");
                rollback(transaction);
            }
        } catch (HibernateException e) {
            logger.error("Can not update tiempo aire status", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updateStatus() ", e);
            rollback(transaction);
        }
        return success;
    }

    /**
     * Save a new tiempo entry.
     *
     * @param tiempo
     * @return
     */
    public boolean save(TiempoAire tiempo) {
        logger.info("save");

        boolean success = false;
        Transaction transaction = null;

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

            session.save(tiempo);

            transaction.commit();
            success = true;
        } catch (HibernateException e) {
            logger.error("Can not save tiempo aire entry", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method save()", e);
            rollback(transaction);
        }
        return success;
    }

    private static final long serialVersionUID = -8772793021819350069L;
    final Logger logger = LogManager.getLogger(TiempoAireController.class);
}
