/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.taxiservicios.services.sale;

import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.admin.Sale;
import com.arrebol.taxiservicios.model.admin.Taxi;
import javax.enterprise.context.RequestScoped;
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 Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@RequestScoped
public class SaleServiceImpl implements SaleService {

    @Override
    public boolean addSale(Sale sale) {
        logger.info("addSale");
        boolean success = false;

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

            Taxi taxi = session.find(Taxi.class, sale.getTaxi().getId());

            if (null != taxi) {
                sale.setPayDayAsSpected(taxi.getPayDay());
                sale.setPaySavingAsSpected(taxi.getPaySaving());
                sale.setAccidentAsSpected(taxi.getPayAccident());
                sale.setTotalToPay(taxi.getPayDay() + taxi.getPaySaving() + taxi.getPayAccident());
            } else {
                if (null != transaction) {
                    transaction.rollback();
                }
                return false;
            }
            /*
            sale.setCreatedBy(new User(userId, ""));
            sale.setPerson(new Person(driverId));
            sale.setTaxi(new Taxi(idTaxi));
             */
            session.save(sale);
            transaction.commit();
            logger.info("Sale saved " + sale.getId());

            success = true;
        } catch (HibernateException e) {
            logger.error("Sale can not be added ", e);
            if (null != transaction) {
                transaction.rollback();
            }
        } catch (Exception e) {
            logger.error("Method addSale() ", e);
            if (null != transaction) {
                transaction.rollback();
            }
        }
        return success;
    }

    final Logger logger = LogManager.getLogger(getClass());

}
