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

import com.arrebol.taxiservicios.controller.util.FilterMap;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.controller.util.LazyDataModelDAORepository;
import com.arrebol.taxiservicios.model.admin.Transfer;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.view.admin.TransferView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaUpdate;
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;
import org.hibernate.query.NativeQuery;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@RequestScoped
public class TransferServiceImpl extends LazyDataModelDAORepository<TransferView> implements TransferService {

    @Override
    public long countPaginator(Map<String, Object> filterBy) {
        logger.debug("countPaginator");
        try {
            StringBuilder sqlQuery = new StringBuilder("SELECT COUNT(id) FROM TransferView ");

            sqlQuery.append(FilterMap.genericFilterByMapping(filterBy, false));

            return lazyLoadingEntityCount(sqlQuery.toString(), null);
        } catch (Exception e) {
            logger.error("countPaginator", e);

            return 0l;
        }
    }

    @Override
    public List<TransferView> lazyEntityListPaginator(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filterBy) {
        logger.debug("fillListPaginator");
        try {
            StringBuilder sqlQuery = new StringBuilder("FROM TransferView ");

            sqlQuery.append(FilterMap.genericFilterByMapping(filterBy, false));
            sqlQuery.append(" ORDER BY ");

            if (null == sortField || "".equals(sortField)) {
                sqlQuery.append(" transferDate DESC");
            } else {
                sqlQuery.append(sortField);
                if (null != sortOrder) {
                    sqlQuery.append(" ");
                    sqlQuery.append(sortOrder.equals(SortOrder.ASCENDING) ? "ASC" : "DESC");
                } else {
                    sqlQuery.append(" DESC");
                }
            }

            return lazyLoadingEntityList(TransferView.class, sqlQuery.toString(), null, first, pageSize);
        } catch (Exception e) {
            logger.error("lazyEntityListPaginator", e);
            return new ArrayList();
        }
    }

    @Override
    public boolean updateTransferTStatus(String id, BasicType status, User lastUpdatedBy) {
        logger.debug("updateTransferTStatus");

        boolean success = false;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaUpdate<Transfer> query = builder.createCriteriaUpdate(Transfer.class);
            Root<Transfer> root = query.from(Transfer.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.debug("Update status successfully");
            } else {
                logger.debug("CAN NOT update transfer status");
                if (null != transaction) {
                    transaction.rollback();
                }
            }
        } catch (HibernateException e) {
            logger.error("Can not update transfer status", e);
            if (null != transaction) {
                transaction.rollback();
            }
        } catch (Exception e) {
            logger.error("Method updateTransferTStatus() ", e);
            if (null != transaction) {
                transaction.rollback();
            }
        }
        return success;
    }

    @Override
    public boolean saveTransfer(Transfer transfer) {
        boolean success = false;
        Transaction transaction = null;

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

            session.save(transfer);
            transaction.commit();

            success = true;

            logger.debug("New record was inserted in Transfer");
        } catch (HibernateException e) {
            logger.error("Can not insert a transfer event", e);
            if (null != transaction) {
                transaction.rollback();
            }
        } catch (Exception e) {
            logger.error("Method saveTransfer()", e);
            if (null != transaction) {
                transaction.rollback();
            }
        }
        return success;
    }

    @Override
    public List<User> findAllSystemUser() {
        logger.debug("Searching all findAllSystemUser..");

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

            String query = "SELECT usr FROM User usr "
                    + " WHERE "
                    + " usr.userStatusType = 'ENABLED' "
                    + " AND usr.active = true "
                    + " ORDER BY usr.createdOn DESC";

            result = session.createQuery(query, User.class).getResultList();

            transaction.commit();
            logger.debug("Total of find All System User found for ComboBox: " + (null == result ? -1 : result.size()));
        } catch (HibernateException e) {
            logger.error("Can not load list of find All System User  for ComboBox ", e);
            if (null != transaction) {
                transaction.rollback();
            }
        } catch (Exception e) {
            logger.error("Method findAllSystemUser of Expense", e);
            if (null != transaction) {
                transaction.rollback();
            }
        }
        return result;
    }


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

    @Override
    public List<TransferView> lazyEntityListPaginator(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filterBy, String idlocation) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public long countPaginator(Map<String, Object> filterBy, String idLocation) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}
