/*
 * 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.Brand;
import com.arrebol.taxiservicios.model.catalog.Vehicle;
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 ModelVehicleController extends ConnectionManager implements Serializable {

    /**
     *
     * Searching all colors.
     *
     * @return
     */
    public List<Vehicle> fillModelVehicleDatatable() {

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

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

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

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

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

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

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

        return result;
    }

    public void saveModelVehicle(Vehicle vehicle, String userId, String brandId) {
        Transaction transaction = null;

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

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

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

                session.createQuery(update).executeUpdate();

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

                vehicle.setId(UUID.randomUUID().toString());
                vehicle.setCreatedBy(new User(userId, ""));
                vehicle.setCreatedOn(new Date());
                vehicle.setBrand(new Brand(brandId));

                session.save(vehicle);
                logger.info("The model vehicle was saved - " + vehicle);
            }

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

    public void deleteModelVehicle(Vehicle vehicle) {

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

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

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

                session.createQuery(delete).executeUpdate();

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

    private static final long serialVersionUID = -5695057885682423164L;

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

    public ModelVehicleController() {
    }
}
