/*
 * 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.ExpenseCompany;
import com.arrebol.taxiservicios.model.admin.Taxes;
import com.arrebol.taxiservicios.model.catalog.BankCard;
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.enums.ExpenseStatusType;
import com.arrebol.taxiservicios.model.enums.TaxesType;
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 TaxesController extends ConnectionManager implements Serializable {

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

        Transaction transaction = null;

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

            Path<String> id = root.get("id");
            Path<BigDecimal> amount = root.get("amount");
            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");
            Path<TaxesType> taxesTypePath = root.get("taxesType");

            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(Taxes.class, id, amount, description, createdOn, createdByPath, locationPath, activeStatusPath, taxesTypePath));
            query.where(builder.and(
                    startDatePredicate, endDatePredicate, locationPredicate
            ));
            query.orderBy(builder.asc(root.get("createdOn")));

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

            transaction.commit();

            logger.info("Taxes's list " + results.size());
        } catch (HibernateException e) {
            logger.error("Can not load taxes list ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findTaxesBetweenDates() ", e);
            rollback(transaction);
        }
        return results;
    }

    public List<Taxes> findTaxesPending(String idLocation) {
        logger.info("findTaxesBetweenDates");
        List<Taxes> results = new ArrayList<>();

        Transaction transaction = null;

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

            // Path<String> id = root.get("id");
            // Path<BigDecimal> amount = root.get("amount");
            // 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");
            //Path<TaxesType> taxesTypePath = root.get("taxesType");
            Predicate pending = builder.equal(root.get("depositStatus"), ExpenseStatusType.PENDING);
            Predicate bankCardNotNull = builder.isNotNull(root.get("bankCard"));

            Predicate locationPredicate = builder.equal(root.get("location"), new Location(idLocation));

            //query.select(builder.construct(Taxes.class, id, amount, description, createdOn, createdByPath, locationPath, activeStatusPath, taxesTypePath));
            query.where(builder.and(
                    pending, bankCardNotNull, locationPredicate
            ));
            query.orderBy(builder.desc(root.get("createdOn")));

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

            transaction.commit();

            logger.info("Taxes's list " + results.size());
        } catch (HibernateException e) {
            logger.error("Can not load taxes list ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findTaxesBetweenDates() ", e);
            rollback(transaction);
        }
        return results;
    }

    public boolean autorizarExpense(String expenseId, User user) {
        logger.info("autorizar");

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

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

            update.set("depositStatus", ExpenseStatusType.AUTHORIZED);
            update.set("lastUpdatedBy", user);
            update.set("lastUpdatedOn", new Date());
            update.where(builder.equal(rootUpdate.get("id"), expenseId));

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

            if (1 == total) {
                transaction.commit();
                success = true;
                logger.info("ExpenseCompany " + expenseId + " updated");
            } else {
                transaction.rollback();
                logger.error("Error ExpenseCompany updated total: " + total);
            }
        } catch (HibernateException e) {
            logger.error("ExpenseCompany can not be updated ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method autorizar() ", e);
            rollback(transaction);
        }
        return success;
    }

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

        boolean success = false;
        Transaction transaction = null;

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

    /**
     * Save a new taxes entry.
     *
     * @param taxes
     * @return
     */
    public boolean saveTaxes(Taxes taxes) {
        logger.info("saveTaxes");

        boolean success = false;
        Transaction transaction = null;

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

            session.save(taxes);

            transaction.commit();
            success = true;
        } catch (HibernateException e) {
            logger.error("Can not save taxes entry", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method saveTaxes()", e);
            rollback(transaction);
        }
        return success;
    }

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