/*
 * 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.core.User;
import com.arrebol.taxiservicios.model.enums.BrandType;
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 CarBrandController extends ConnectionManager implements Serializable {

    /**
     *
     * Searching all products brand.
     *
     * @return
     */
    public List<Brand> fillCarBrandDatatable() {

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

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

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

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

            criteria.select(
                    builder.construct(Brand.class, idPath, namePath
                    ));
            criteria.where(builder.equal(root.get("brandType"), BrandType.VEHICLE));

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

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

        return result;
    }

    public void saveCarBrand(Brand brand, String userId) {
        Transaction transaction = null;

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

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

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

                session.createQuery(update).executeUpdate();

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

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

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

    public void deleteCarBrand(Brand brand) {

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

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

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

                session.createQuery(delete).executeUpdate();

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

    public List<Brand> fillCarBrandComboBox() {

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

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

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

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

            criteria.select(
                    builder.construct(Brand.class, idPath, namePath
                    ));
            criteria.where(builder.equal(root.get("brandType"), BrandType.VEHICLE));

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

            logger.info("Total of car brands found for ComboBox: " + (null == result ? -1 : result.size()));
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("Can not load list of car brands for ComboBox ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillCarBrandComboBox of CarBrand", e);
            rollback(transaction);
        }

        return result;
    }

    private static final long serialVersionUID = -7855507530688616481L;

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

    public CarBrandController() {
    }

}
