/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arrebol.taxiservicios.controller.catalog;

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.catalog.BankCard;
import com.arrebol.taxiservicios.model.catalog.BankCardKardex;
import com.arrebol.taxiservicios.model.catalog.Location;
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 java.util.UUID;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Path;
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 oscarvargas
 */
public class BankCardController extends ConnectionManager implements Serializable {

    /**
     *
     * Searching all BankCard.
     *
     * @param location
     * @return
     */
    public List<BankCard> fillDatatable(Location location) {
    Transaction transaction = null;
    List<BankCard> result = null;

    try {
        logger.info("Searching all colors..");
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        transaction = session.beginTransaction();
        CriteriaBuilder builder = session.getCriteriaBuilder();

        CriteriaQuery<BankCard> criteria = builder.createQuery(BankCard.class);
        Root<BankCard> root = criteria.from(BankCard.class);

        Path<String> idPath = root.get("id");
        Path<String> bank = root.get("bank");
        Path<String> titular = root.get("titular");
        Path<String> numero = root.get("numero");
        Path<String> balance = root.get("balance");

        criteria.select(
            builder.construct(BankCard.class, idPath, bank, titular, numero, balance)
        );
        
        criteria.where(
            builder.and(
                builder.equal(root.get("activeStatus"), BasicType.ENEBLED),
                builder.equal(root.get("location"), location)  // Agregar filtro por ubicación
            )
        );
        
        result = session.createQuery(criteria).getResultList();

        logger.info("Total of BankCard found : " + (null == result ? -1 : result.size()));
        transaction.commit();
    } catch (HibernateException e) {
        logger.error("Can not load list of BankCard ", e);
        rollback(transaction);
    } catch (Exception e) {
        logger.error("Method fillDatatable of BankCard", e);
        rollback(transaction);
    }

    return result;
}

    public void save(BankCard bankCard, String userId) {
        Transaction transaction = null;

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

            if (bankCard.getId() != null) {
                CriteriaUpdate<BankCard> update = builder.createCriteriaUpdate(BankCard.class);
                Root<BankCard> root = update.from(BankCard.class);

                update.set("bank", bankCard.getBank());
                update.set("titular", bankCard.getTitular());
                update.set("numero", bankCard.getNumero());
                update.set("balance",bankCard.getBalance());
                update.set("lastUpdatedBy", new User(userId, ""));
                update.set("lastUpdatedOn", new Date());
                update.where(builder.equal(root.get("id"), bankCard.getId()));

                session.createQuery(update).executeUpdate();

                logger.info("The bankCard was edited - " + bankCard);
            } else {

                bankCard.setId(UUID.randomUUID().toString());
                bankCard.setCreatedBy(new User(userId, ""));
                bankCard.setCreatedOn(new Date());
                session.save(bankCard);
                logger.info("The BankCard was saved - " + bankCard);
            }

            transaction.commit();
        } catch (HibernateException e) {
            logger.error("The BankCard can not be saved - " + bankCard, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method save(" + bankCard + ")", e);
            rollback(transaction);
        }
    }

    public void delete(BankCard bankCard, String userId) {

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            if (bankCard.getId() != null) {
                CriteriaUpdate<BankCard> update = builder.createCriteriaUpdate(BankCard.class);
                Root<BankCard> root = update.from(BankCard.class);

                update.set("activeStatus", BasicType.DISABLED);
                update.set("lastUpdatedBy", new User(userId, ""));
                update.set("lastUpdatedOn", new Date());
                update.where(builder.equal(root.get("id"), bankCard.getId()));

                session.createQuery(update).executeUpdate();

                logger.info("The bankCard was deleted - " + bankCard.getId());
            }
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("The bankCard can not be deleted - " + bankCard, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method  delete(" + bankCard + ")", e);
            rollback(transaction);
        }
    }

    /**
     *
     * @param locationId
     * @return
     */
    public List<BankCard> findAllBankCardsByLocation(String locationId) {

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

        try {
            logger.info("Searching all colors..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

            CriteriaQuery<BankCard> criteria = builder.createQuery(BankCard.class);
            Root<BankCard> root = criteria.from(BankCard.class);

            Path<String> idPath = root.get("id");
            Path<String> bank = root.get("bank");
            Path<String> titular = root.get("titular");
            Path<String> numero = root.get("numero");

            criteria.select(
                    builder.construct(BankCard.class, idPath, bank, titular, numero
                    ));
            criteria.where(
                    builder.and(
                            builder.equal(root.get("activeStatus"), BasicType.ENEBLED),
                            builder.equal(root.get("location"), new Location(locationId))
                    ));
            result = session.createQuery(criteria).getResultList();

            logger.info("Total of BankCard found : " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load list of BankCard ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillDatatable of BankCard", e);
            rollback(transaction);
        }

        return result;
    }

    private static final long serialVersionUID = -559465932081273592L;

    final Logger logger = LogManager.getLogger(BankCardController.class);

    public BankCardController() {
    }

}
