/*
 * 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.controller.lazy.services;

import com.arrebol.taxiservicios.controller.util.FilterMap;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.controller.util.LazyDataModelDAORepository;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.view.dashboard.InsuranceDashboardListView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaUpdate;
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;
import org.primefaces.model.SortOrder;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@RequestScoped
public class InsuranceServiceImpl extends LazyDataModelDAORepository<InsuranceDashboardListView> implements InsuranceService {

    @Override
    public long countPaginator(Map<String, Object> filterBy, String idLocation) {
        logger.debug("countPaginator");
        try {
            StringBuilder sqlQuery = new StringBuilder("SELECT COUNT(id) FROM InsuranceDashboardListView WHERE id_location ='"+idLocation+"'");

            sqlQuery.append(FilterMap.genericFilterByMapping(filterBy, true));

            return lazyLoadingEntityCount(sqlQuery.toString(), null);
        } catch (Exception e) {
            logger.error("countPaginator", e);

            return 0l;
        }
    }

    @Override
    public List<InsuranceDashboardListView> lazyEntityListPaginator(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filterBy, String idLocation) {
        logger.debug("fillListPaginator");
        try {
            StringBuilder sqlQuery = new StringBuilder("FROM InsuranceDashboardListView WHERE id_location ='"+idLocation+"'");

            sqlQuery.append(FilterMap.genericFilterByMapping(filterBy, true));
            sqlQuery.append(" ORDER BY ");

            if (null == sortField || "".equals(sortField)) {
                sqlQuery.append(" insuranceEndDate ASC");
            } else {
                sqlQuery.append(sortField);
                if (null != sortOrder) {
                    sqlQuery.append(" ");
                    sqlQuery.append(sortOrder.equals(SortOrder.ASCENDING) ? "ASC" : "DESC");
                } else {
                    sqlQuery.append(" ASC");
                }
            }

            return lazyLoadingEntityList(InsuranceDashboardListView.class, sqlQuery.toString(), null, first, pageSize);
        } catch (Exception e) {
            logger.error("lazyEntityListPaginator", e);
            return new ArrayList();
        }
    }

    @Override
    public boolean updateInsuranceInformation(String seguro, String cobertura, Date fecha, String id, String numero) {
        logger.debug("updateInsuranceInformation");

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

            /**
             * Taxi Servicios goes for user details.
             */
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaUpdate<Taxi> update = builder.createCriteriaUpdate(Taxi.class);
            Root<Taxi> rootPerson = update.from(Taxi.class);

            update.set("insuranceName", seguro);
            update.set("insuranceCobertura", cobertura);
            update.set("insuranceEndDate", fecha);
            update.set("insuranceNumber", numero);

            update.where(builder.equal(rootPerson.get("id"), id));

            int total = session.createQuery(update).executeUpdate();

            if (1 == total) {
                logger.debug("Taxi updated taxi_id: " + id);
                transaction.commit();

                success = true;
            } else {
                logger.error("Taxi can not be updated " + id);
                transaction.rollback();
            }
        } catch (HibernateException e) {
            logger.error("Taxi cannot be updated " + id, e);
            if (null != transaction) {
                transaction.rollback();
            }
        } catch (Exception e) {
            logger.error("Method updateInsuranceInformation(" + id + ") ", e);
            if (null != transaction) {
                transaction.rollback();
            }
        }
        return success;
    }

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

    @Override
    public List<InsuranceDashboardListView> lazyEntityListPaginator(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filterBy) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public long countPaginator(Map<String, Object> filterBy) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}
