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

import 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.ActionStatus;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.mutual.TransferMutual;
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 TransferMutualController extends ConnectionManager implements Serializable {
    
   public List<TransferMutual> findAllTransfer() {
        logger.info("findAllTransfer");

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

        try {
            logger.info("Searching all transfer..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            String hql = "SELECT transfer FROM TransferMutual transfer WHERE transfer.activeStatus = :activeStatus";
            Query query = session.createQuery(hql, TransferMutual.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<TransferMutual> findAllTransferPendingByUser(User userReceiver) {
        logger.info("findAllTransfer");

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

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

            result = session.createQuery("SELECT transfer FROM TransferMutual transfer WHERE transfer.activeStatus = :activeStatus "+
                    "AND transfer.actionStatus = 'PENDING' AND transfer.userReceiver = :userReceiver")
                  
                    .setParameter("activeStatus", BasicType.ENEBLED)
                    .setParameter("userReceiver", userReceiver)
                    .getResultList();

            transaction.commit();
            logger.info("Total of Transfer founds in auto complete search " + result.size());
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Can not load auto complete list of Transfers", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method findAllTransferPendingByUser", e);
        }

        return result;
    }
    
    
    public boolean validateTransferMutualPending(User userReceiver) {
        logger.info("findAllTransfer");

        Transaction transaction = null;
        boolean result = false;

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

            Query query = session.createQuery("SELECT COUNT(transfer) FROM TransferMutual transfer WHERE transfer.activeStatus = :activeStatus "+
                    "AND transfer.actionStatus = 'PENDING' AND transfer.userReceiver = :userReceiver")
                  
                    .setParameter("activeStatus", BasicType.ENEBLED)
                    .setParameter("userReceiver", userReceiver);
            
            Long count = (Long)query.uniqueResult();

            if(count  == 0) result = true;
            
            transaction.commit();
            ;
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Can not load auto complete list of Transfers", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method findAllTransferPendingByUser", e);
        }

        return result;
    }
   
     public boolean autorizar(String transferMutualId, User userUpdate) {
        logger.info("autorizar");

        boolean success = false;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaUpdate<TransferMutual> update = builder.createCriteriaUpdate(TransferMutual.class);
            Root<TransferMutual> rootUpdate = update.from(TransferMutual.class);

            update.set("actionStatus", ActionStatus.APPROVED);
            update.set("lastUpdatedBy", userUpdate);
            update.set("lastUpdatedOn", new Date());
            update.where(builder.equal(rootUpdate.get("id"), transferMutualId));

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

            if (1 == total) {
                transaction.commit();
                success = true;
                logger.info("Transfer Mutual " + transferMutualId + " updated");
            } else {
                transaction.rollback();
                logger.error("Error Sale updated total: " + total);
            }
        } catch (HibernateException e) {
            logger.error("Sanction can not be updated ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method autorizar() ", e);
            rollback(transaction);
        }
        return success;
    }
    
   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(TransferMutual 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<TransferMutual> query = builder.createCriteriaUpdate(TransferMutual.class);
            Root<TransferMutual> root = query.from(TransferMutual.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(TransferMutualController.class);
    private static final long serialVersionUID = -6732331411572526429L;
}
