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

import com.arrebol.apc.controller.util.FilterMap;
import com.arrebol.apc.controller.util.HibernateUtil;
import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.views.CustomerWithoutRenovationView;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.persistence.Query;
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 CustomerWithoutRenovationViewServiceImpl implements CustomerWithoutRenovationViewService {

    @Override
    public Long countAllCustomerWithOutRenovationByOfficePaginator(String officeId, String filterBy, Map<String, Object> map) {
        logger.debug("countAllCustomerWithOutRenovationByOfficePaginator");

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

            StringBuilder sqlQuery = new StringBuilder("SELECT COUNT(id) FROM CustomerWithoutRenovationView ");
            
            sqlQuery.append(buildQueryForCustomerWithoutRenovationView(filterBy, map));

            result = session
                    .createQuery(sqlQuery.toString(), Long.class)
                    .setParameter("office", new Office(officeId))
                    .getSingleResult();

            transaction.commit();
        } catch (HibernateException e) {
            logger.error("countAllCustomerWithOutRenovationByOfficePaginator Hibernate", e);
            if (null != transaction) {
                transaction.rollback();
            }
            throw e;
        } catch (Exception e) {
            logger.error("Method countAllCustomerWithOutRenovationByOfficePaginator() ", e);
            if (null != transaction) {
                transaction.rollback();
                throw e;
            }
        } finally {
            if (null != session) {
                session.close();
            }
        }
        return result;
    }

    @Override
    public List<CustomerWithoutRenovationView> findAllCustomerWithOutRenovationByOfficePaginator(String officeId, int first, int pageSize, String filterBy, String sortBy, String sorting, Map<String, Object> map) {
        logger.debug("findAllCustomerWithOutRenovationByOfficePaginator");

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

            StringBuilder sqlQuery = new StringBuilder("FROM CustomerWithoutRenovationView ");
            
            sqlQuery.append(buildQueryForCustomerWithoutRenovationView(filterBy, map));
            sqlQuery.append(" ORDER BY ");

            if (null == sortBy || "".equals(sortBy)) {
                sqlQuery.append("personName ASC");
            } else {
                sqlQuery.append(sortBy);
                sqlQuery.append(" ");
                sqlQuery.append(sorting);
            }

            Query query = session.createQuery(sqlQuery.toString(), CustomerWithoutRenovationView.class);

            query.setFirstResult(first);
            query.setMaxResults(pageSize);

            results = query.setParameter("office", new Office(officeId)).getResultList();

            transaction.commit();
        } catch (HibernateException e) {
            logger.error("findAllCustomerWithOutRenovationByOfficePaginator Hibernate", e);
            if (null != transaction) {
                transaction.rollback();
            }
            throw e;
        } catch (Exception e) {
            logger.error("Method findAllCustomerWithOutRenovationByOfficePaginator() ", e);
            if (null != transaction) {
                transaction.rollback();
            }
            throw e;
        } finally {
            if (null != session) {
                session.close();
            }
        }
        return results;
    }

    /**
     *
     * @param filterBy
     * @param map
     * @return
     */
    private StringBuilder buildQueryForCustomerWithoutRenovationView(
            String filterBy, Map<String, Object> map) {
        StringBuilder sqlQuery = new StringBuilder("WHERE office = :office ");

        if (null != filterBy & !"".equals(filterBy)) {
            sqlQuery.append("AND (personName LIKE '");
            sqlQuery.append(filterBy);
            sqlQuery.append("' OR ");

            sqlQuery.append("routeName LIKE '");
            sqlQuery.append(filterBy);
            sqlQuery.append("' OR ");

            sqlQuery.append("strPaymentDate LIKE '");
            sqlQuery.append(filterBy);
            sqlQuery.append("') ");
        }

        sqlQuery.append(FilterMap.genericFilterByMapping(map, true));

        return sqlQuery;
    }

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