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

    public TipoPolizaController() {
    }

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

        Transaction transaction = null;

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

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

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

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

            transaction.commit();

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

   

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

        boolean success = false;
        Transaction transaction = null;

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

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

        boolean success = false;
        Transaction transaction = null;

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

            session.save(tipoPoliza);

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

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

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

                update.set("name", tipoPoliza.getName());
                update.set("costo", tipoPoliza.getCosto());
                update.set("costoSemestral", tipoPoliza.getCostoSemestral());
                update.set("costoTrimestral", tipoPoliza.getCostoTrimestral());
                update.set("costoMensual", tipoPoliza.getCostoMensual());
                update.set("lastUpdatedBy", new User(userId, ""));
                update.set("lastUpdatedOn", new Date());
                update.where(builder.equal(root.get("id"), tipoPoliza.getId()));

                session.createQuery(update).executeUpdate();

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

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

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

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