/*
 * 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.stocktaking;

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.catalog.Color;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.catalog.Vehicle;
import com.arrebol.taxiservicios.model.stocktaking.TransferVehicle;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
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 Oscar
 */
public class TransferVehicleController extends ConnectionManager implements Serializable {
    
    public List<Taxi> fillVehicleComboBox() {

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

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

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

            Path<String> idPath = root.get("id");
            Path<String> placa = root.get("placa");
            Path<String> year = root.get("year");
            Path<Vehicle> vehicle = root.get("vehicle");
            Path<Color> color = root.get("color");

            criteria.select(
                    builder.construct(Taxi.class, idPath, placa, year, vehicle, color
                    ));
            criteria.where(builder.equal(root.get("active"), Boolean.TRUE));

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

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

        return result;
    }
    
    public List<Location> fillLocationComboBox() {
        logger.info("Searching all locations to select..");

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

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

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

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

            criteria.select(
                    builder.construct(Location.class, idPath, namePath
                    ));

            criteria.where(builder.equal(root.get("active"), Boolean.TRUE));

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

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

        return result;
    }
    
    public List<TransferVehicle> fillDataTableBetweenDates(Date starDate, Date endDate, Location location) {
        logger.info("fillDataTableBetweenDates");

        List<TransferVehicle> results = null;
        Transaction transaction = null;

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

            results = session.createQuery("FROM TransferVehicle WHERE (DATE(createdOn) BETWEEN DATE(:starDate) AND DATE(:endDate)) AND location.id = :location  ORDER BY createdOn DESC")
                    .setParameter("starDate", starDate)
                    .setParameter("endDate", endDate)
                    .setParameter("location", location.getId())
                    .getResultList();

            transaction.commit();
            logger.info("Total of TransferVehicle founds in auto complete search " + results.size());
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Can not load auto complete list of TransferVehicle", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method fillDataTableBetweenDates", e);
        }

        return results;
    }
    
    public boolean save(TransferVehicle transferVehicle) {
        logger.info("save");

        boolean success = false;
        Transaction transaction = null;

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

            session.save(transferVehicle);
            logger.info("transferVehicle saved " + transferVehicle.getId());

            transaction.commit();

            success = true;
        } catch (HibernateException e) {
            logger.error("transferVehicle can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method save() ", e);
            rollback(transaction);
        }
        return success;
    }
    
    public Taxi findById(String id) {
        Taxi result = null;
        Transaction transaction = null;

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

            result = session.find(Taxi.class, id);

            transaction.commit();
        } catch (HibernateException e) {
            rollback(transaction);
            logger.error("Can not found stocktaking invoice by id", e);
        } catch (Exception e) {
            rollback(transaction);
            logger.error("Method findStocktakingInvoiceById", e);
        }

        return result;
    }
    
     final Logger logger = LogManager.getLogger(TransferVehicleController.class);

    public TransferVehicleController() {
    }
}
