/*
 * 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 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 HospitalesController extends ConnectionManager implements Serializable {

    public HospitalesController() {
    }

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

        Transaction transaction = null;

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

            Predicate hospitalesActives = builder.equal(root.get("active"), Boolean.TRUE);
            
            query.where(builder.and(
                    hospitalesActives
            ));
            query.orderBy(builder.asc(root.get("createdOn")));

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

            transaction.commit();

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

   

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

        boolean success = false;
        Transaction transaction = null;

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

    /**
     * Save a new hospitales entry.
     *
     * @param hospitales
     * @return
     */
    public boolean saveHospitales(Hospitales hospitales) {
        logger.info("saveHospitales");

        boolean success = false;
        Transaction transaction = null;

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

            session.save(hospitales);

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

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

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

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

                session.createQuery(update).executeUpdate();

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

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

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

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