/*
 * 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.Transfer;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
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.Query;

/**
 *
 * @author Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
public class TransferController extends ConnectionManager implements Serializable {
    
   public List<Transfer> findAllTransfer() {
        logger.info("findAllTransfer");

        Transaction transaction = null;
        List<Transfer> result = null;

        try {
            logger.info("Searching all transfer..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            String hql = "SELECT transfer FROM Transfer transfer WHERE transfer.activeStatus = :activeStatus";
            Query query = session.createQuery(hql, Transfer.class);

            query.setParameter("activeStatus", BasicType.ENEBLED);

            result = query.getResultList();
            transaction.commit();
            logger.info("Total of transfer found : " + (null == result ? -1 : result.size()));
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Can not load list of find All Transfer ", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method findAllTransfer", e);
        }

        return result;
    }
   
   public List<User> findAllSystemUser() {
        logger.info("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.info("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);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findAllSystemUser of Expense", e);
            rollback(transaction);
        }

        return result;
    }
    
    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.info("New record was inserted in Transfer");
        } catch (HibernateException e) {
            logger.error("Can not insert a transfer event", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method saveTransfer()", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean updateTransferTStatus(String id, BasicType status, User lastUpdatedBy) {
        logger.info("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.info("Update status successfully");
            } else {
                logger.info("CAN NOT update transfer status");
                rollback(transaction);
            }
        } catch (HibernateException e) {
            logger.error("Can not update transfer status", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updateTransferTStatus() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    final Logger logger = LogManager.getLogger(TransferController.class);
    private static final long serialVersionUID = -6732331411572526429L;
}
