/*
 * 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.TipoSiniestro;
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.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 TipoSiniestroController extends ConnectionManager implements Serializable {

    public TipoSiniestroController() {
    }

    /**
     *
     * @return List of all hospitales.
     */
    public List<TipoSiniestro> findTipoSiniestro() {
        logger.info("findTipoSiniestro");
        List<TipoSiniestro> resultList = null;
        Transaction transaction = null;
        try {
            logger.info("Searching tipo siniestro for lote..");
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();

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

            Predicate tipoSiniestroActives = builder.equal(root.get("active"), Boolean.TRUE);
            criteria.where(builder.and(tipoSiniestroActives));
            criteria.orderBy(builder.desc(root.get("createdOn")));

            resultList = session.createQuery(criteria).getResultList();

            logger.info("Total of tipo siniestro found: " + (null == resultList ? -1 : resultList.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Tipo siniestro cannot be loade ");
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findTipoSiniestro ", e);
            rollback(transaction);
        }
        return resultList;
    }

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

        boolean success = false;
        Transaction transaction = null;

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

    /**
     * Save a new tipoSiniestro entry.
     *
     * @param tipoSiniestro
     * @return
     */
    public boolean saveTipoSiniestro(TipoSiniestro tipoSiniestro) {
        logger.info("saveTipoSiniestro");

        boolean success = false;
        Transaction transaction = null;

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

            session.save(tipoSiniestro);

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

    public void saveTipoSiniestro(TipoSiniestro tipoSiniestro, String userId) {
        logger.info("saveTipoSiniestro");
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            if (tipoSiniestro.getId() == null) {
                tipoSiniestro.setId(UUID.randomUUID().toString());
                tipoSiniestro.setActive(true);
                tipoSiniestro.setCreatedBy(new User(userId, ""));
                tipoSiniestro.setCreatedOn(new Date());
                session.save(tipoSiniestro);
                transaction.commit();
                logger.info("Tipo siniestro saved " + tipoSiniestro.getId());
            } else {
                tipoSiniestro.setLastUpdatedOn(new Date());
                tipoSiniestro.setLastUpdatedBy(new User(userId, ""));
                session.update(tipoSiniestro);
                transaction.commit();
                logger.info("Tipo siniestro updated " + tipoSiniestro.getId());
            }
        } catch (HibernateException e) {
            logger.error("Tipo siniestro can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method saveTipoSiniestro() ", e);
            rollback(transaction);
        }
    }

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