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

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

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

        try {
            logger.info("Searching all product 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.OTHER));

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

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

        return result;
    }

    public boolean saveProductBrand(Brand brand, String userId) {
        boolean success = false;
        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 product brand was edited - " + brand);
            } else {

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

            transaction.commit();
            success = true;
        } catch (HibernateException e) {
            logger.error("The product brand can not be saved - " + brand, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method saveProductBrand(" + brand + ")", e);
            rollback(transaction);
        }
        return success;
    }

    public void deleteProductBrand(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 product brand was deleted - " + brand.getId());
            }
            transaction.commit();
        } catch (HibernateException e) {
            logger.error("The product brand can not be deleted - " + brand, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method  deleteProductBrand(" + brand + ")", e);
            rollback(transaction);
        }
    }

    /**
     *
     * @return
     */
    public List<Brand> fillProductBrandComboBox() {

        Transaction transaction = null;
        List<Brand> result = new ArrayList<>();

        try {
            logger.info("Searching all products 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.OTHER));
            criteria.orderBy(builder.asc(root.get("name")));

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

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

        return result;
    }

    private static final long serialVersionUID = 6362659639985879901L;

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

    public ProductBrandController() {
    }

}
