/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.crov.prase.controller.catalog;

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.core.User;
import com.crov.prase.model.catalog.Hospitales;
import com.crov.prase.model.catalog.Talleres;
import java.io.Serializable;
import java.util.ArrayList;
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 Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
public class TalleresController extends ConnectionManager implements Serializable {

    public TalleresController() {
    }

    /**
     *
     * @return List of all hospitales.
     */
    public List<Talleres> findTalleres() {
        logger.info("findTalleres");
        List<Talleres> results = new ArrayList<>();

        Transaction transaction = null;

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

            Predicate talleresActives = builder.equal(root.get("active"), Boolean.TRUE);

            query.where(builder.and(
                    talleresActives
            ));
            query.orderBy(builder.asc(root.get("createdOn")));

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

            transaction.commit();

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

   

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

        boolean success = false;
        Transaction transaction = null;

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

            query.set(root.get("active"), false);
            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 Talleres status");
                rollback(transaction);
            }
        } catch (HibernateException e) {
            logger.error("Can not update Talleres status", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method deleteTalleres() ", e);
            rollback(transaction);
        }
        return success;
    }

    /**
     * Save a new talleres entry.
     *
     * @param talleres
     * @return
     */
    public boolean saveTalleres(Talleres talleres) {
        logger.info("saveTalleres");

        boolean success = false;
        Transaction transaction = null;

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

            session.save(talleres);

            transaction.commit();
            success = true;
        } catch (HibernateException e) {
            logger.error("Can not save talleres entry", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method saveTalleres()", e);
            rollback(transaction);
        }
        return success;
    }
    
    public void saveTalleres(Talleres talleres, String userId) {
        Transaction transaction = null;

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

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

                update.set("name", talleres.getName());
                update.set("direccion", talleres.getDireccion());
                update.set("telefono", talleres.getTelefono());
                update.set("contacto", talleres.getContacto());
                update.set("location", talleres.getLocation());
                update.set("comentarios", talleres.getComentarios());
                update.set("estado", talleres.getEstado());
                update.set("lastUpdatedBy", new User(userId, ""));
                update.set("lastUpdatedOn", new Date());
                update.where(builder.equal(root.get("id"), talleres.getId()));

                session.createQuery(update).executeUpdate();

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

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

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

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