/*
 * 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.util.HibernateUtil;
import com.arrebol.taxiservicios.model.core.User;
import java.util.Date;
import javax.enterprise.context.RequestScoped;
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>
 */
@RequestScoped
public class ClosingDayServiceImpl implements ClosingDayService {

    @Override
    public boolean existClosingDayByCreatedOn(Date date, User user) {
        logger.info("existClosingDayByCreatedOn");

        boolean success = true;
        Transaction transaction = null;

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

            String query = "SELECT COUNT(ssb.id) "
                    + "FROM ClosingDay ssb "
                    + "WHERE DATE(ssb.createdOn) = DATE(:date) "
                    + "AND ssb.activeStatus = 'ENEBLED' "
                    + "AND ssb.user = :user";

            Long count = (Long) session.createQuery(query)
                    .setParameter("date", date)
                    .setParameter("user", user).uniqueResult();

            if (null != count && count == 0) {
                success = false;
            }

            transaction.commit();

            logger.info("Total of closing day found: " + count);
        } catch (HibernateException e) {
            logger.error("Can not find stable small box by created on", e);
            if (null != transaction) {
                transaction.rollback();
            }
        } catch (Exception e) {
            logger.error("Method existStableSmallBoxByCreatedOn()", e);
            if (null != transaction) {
                transaction.rollback();
            }
        }

        return success;
    }

    final Logger logger = LogManager.getLogger(getClass());
}
