/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
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.Color;
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.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Path;
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 oscarvargas
 */
public class ColorController extends ConnectionManager implements Serializable {

    /**
     *
     * Searching all colors.
     *
     * @return
     */
    public List<Color> fillColorDatatable() {

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

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

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

            Path<String> idPath = root.get("id");
            Path<String> namePath = root.get("name");
            Path<String> createdByPath = root.get("createdBy");
            Path<String> createdOnPath = root.get("createdOn");

            criteria.select(builder.construct(Color.class, idPath, namePath, createdByPath, createdOnPath));

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

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

        return result;
    }

    public void saveColor(Color color, String userId) {
        Transaction transaction = null;

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

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

                update.set("name", color.getName());
                update.set("lastUpdatedBy", new User(userId, ""));
                update.set("lastUpdatedOn", new Date());
                update.where(builder.equal(root.get("id"), color.getId()));

                session.createQuery(update).executeUpdate();

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

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

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

    public void deleteColor(Color color) {

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

            if (color.getId() != null) {
                CriteriaDelete<Color> delete = builder.createCriteriaDelete(Color.class);
                Root<Color> root = delete.from(Color.class);

                delete.where(builder.equal(root.get("id"), color.getId()));

                session.createQuery(delete).executeUpdate();

                logger.info("The color was deleted - " + color.getId());
            }
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("The color can not be deleted - " + color, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method  deleteColorType(" + color + ")", e);
            rollback(transaction);
        }
    }

    private static final long serialVersionUID = -559465932081273592L;

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

    public ColorController() {
    }

}
