/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
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.ClaveProductoServicio;
import com.arrebol.taxiservicios.model.catalog.Color;
import com.arrebol.taxiservicios.model.catalog.Documento;
import com.arrebol.taxiservicios.model.core.User;
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.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 Usuario
 */
public class DocumentoController extends ConnectionManager implements Serializable {

    public List<Documento> fillDocumentoDatatable() {

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

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

            CriteriaQuery<Documento> criteria = builder.createQuery(Documento.class);
            Root<Documento> root = criteria.from(Documento.class);
            criteria.orderBy(builder.desc(root.get("createdOn")));
            result = session.createQuery(criteria).getResultList();

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

        return result;
    }
    
    public List<Documento> fillDocumentoDatatableByIdPredio(String idPredio) {

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

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

        CriteriaQuery<Documento> criteria = builder.createQuery(Documento.class);
        Root<Documento> root = criteria.from(Documento.class);
        
        // Agregar la condición WHERE por ID de predio
        Predicate predioIdPredicate = builder.equal(root.get("predio").get("id"), idPredio);
        criteria.where(predioIdPredicate);
        
        criteria.orderBy(builder.desc(root.get("createdOn")));
        result = session.createQuery(criteria).getResultList();

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

    return result;
}
    
    public boolean addDocumento(Documento documento, User user) {
        logger.info("addDocumento");

        boolean success = false;

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

            if (documento.getId() == null) {
                documento.setId(UUID.randomUUID().toString());
                documento.setCreatedBy(user);
                documento.setCreatedOn(new Date());
                session.save(documento);
                transaction.commit();
                logger.info("Documento saved " + documento.getId());
            } else {
                documento.setLastUpdatedBy(user);
                session.update(documento);
                transaction.commit();
                logger.info("Documento updated " + documento.getId());
            }

            success = true;
        } catch (HibernateException e) {
            logger.error("Documento can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addDocumento() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    private static final long serialVersionUID = 1020525241432403643L;

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

    public DocumentoController() {
    }
}
