/*
 * 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.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.ExpenseCompanyType;
import com.arrebol.taxiservicios.model.mutual.MutualInicios;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
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;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
public class MutualIniciosController extends ConnectionManager implements Serializable {

    /**
     * Find company's expenses by type (PAYMENT IN/OUT) and between start date
     * and end date.
     *
     * @param type
     * @param startDate
     * @param endDate
     * @return List of all company expenses.
     */
    public List<MutualInicios> findExpenseCompanyByTypeAndBetweenDates(ExpenseCompanyType type, Date startDate, Date endDate, String idLocation) {
        logger.info("findExpenseCompanyByTypeAndBetweenDates");
        List<MutualInicios> results = new ArrayList<>();

        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<MutualInicios> query = builder.createQuery(MutualInicios.class);
            Root<MutualInicios> root = query.from(MutualInicios.class);

            Path<String> id = root.get("id");
            Path<BigDecimal> amount = root.get("amount");
            Path<User> user = root.get("user");
            Path<String> description = root.get("description");
            Path<Date> createdOn = root.get("createdOn");
            Path<User> createdByPath = root.get("createdBy");
            Path<Location> locationPath = root.get("location");
            Path<Boolean> activeStatusPath = root.get("activeStatus");

            Predicate searchType = builder.equal(root.get("activeStatus"), BasicType.ENEBLED);
            Predicate startDatePredicate = builder.greaterThanOrEqualTo(root.get("createdOn"), startDate);
            Predicate endDatePredicate = builder.lessThanOrEqualTo(root.get("createdOn"), endDate);
            Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation));

            query.select(builder.construct(MutualInicios.class, id, amount, description, createdOn, createdByPath, locationPath, activeStatusPath, user));
            query.where(builder.and(
                    searchType, startDatePredicate, endDatePredicate, locationPredicate
            ));
            query.orderBy(builder.asc(root.get("createdOn")));

            results = session.createQuery(query).getResultList();

            transaction.commit();

            logger.info("Expense Company's list " + results.size());
        } catch (HibernateException e) {
            logger.error("Can not load  expense company list ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findExpenseCompanyByTypeAndBetweenDates() ", e);
            rollback(transaction);
        }
        return results;
    }

    /**
     * Update active status (ENEBLED/DISABLED) of Expense company ID.
     *
     * @param id
     * @param status
     * @param lastUpdatedBy
     * @return
     */
    public boolean updateExpenseCompanyStatus(String id, BasicType status, User lastUpdatedBy) {
        logger.info("updateExpenseCompanyStatus");

        boolean success = false;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaUpdate<MutualInicios> query = builder.createCriteriaUpdate(MutualInicios.class);
            Root<MutualInicios> root = query.from(MutualInicios.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 expense company status");
                rollback(transaction);
            }
        } catch (HibernateException e) {
            logger.error("Can not update expense company status", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updateExpenseCompanyStatus() ", e);
            rollback(transaction);
        }
        return success;
    }

    /**
     * Save a new expense company entry.
     *
     * @param expenseCompany
     * @return
     */
    public boolean saveExpenseCompany(MutualInicios expenseCompany) {
        logger.info("saveExpenseCompany");

        boolean success = false;
        Transaction transaction = null;

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

            session.save(expenseCompany);

            transaction.commit();
            success = true;
        } catch (HibernateException e) {
            logger.error("Can not save expense company entry", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method saveExpenseCompany()", e);
            rollback(transaction);
        }
        return success;
    }
    
    public List<User> findAllSystemUserByLocation(Location location) {
        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 AND usr.location.id = '"+location.getId()+"' "
                    + " 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;
    }


    private static final long serialVersionUID = -8772793021819350069L;
    final Logger logger = LogManager.getLogger(MutualIniciosController.class);
}
