/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rjconsultores.ventaboletos.dao.hibernate;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.rjconsultores.ventaboletos.dao.DiagramaAutobusDAO;
import com.rjconsultores.ventaboletos.entidad.DiagramaAutobus;

/**
 *
 * @author Administrador
 */
@Repository("diagramaAutobusDAO")
public class DiagramaAutobusHibernateDAO extends GenericHibernateDAO<DiagramaAutobus, Short>
        implements DiagramaAutobusDAO {

	private static final Logger log = LogManager.getLogger(DiagramaAutobusHibernateDAO.class);

    @Autowired
    public DiagramaAutobusHibernateDAO(@Qualifier("sessionFactory") SessionFactory factory) {
        setSessionFactory(factory);
    }

    @Override
    public List<DiagramaAutobus> obtenerTodos() {
        Criteria c = getSession().createCriteria(getPersistentClass());
        c.add(Restrictions.eq(ACTIVO, Boolean.TRUE));
        c.addOrder(Order.asc("descDiagrama"));

        return c.list();
    }

    public List<DiagramaAutobus> buscar(String descDiagrama, Short maxparados,
            Short cantasientos) {
        Criteria c = getSession().createCriteria(getPersistentClass());
        c.add(Restrictions.eq(ACTIVO, Boolean.TRUE));

        c.add(Restrictions.eq("cantasientos", cantasientos));
        c.add(Restrictions.eq("maxparados", maxparados));
        c.add(Restrictions.eq("descDiagrama", descDiagrama));

        return c.list();
    }

    public List<DiagramaAutobus> buscar(String descDiagrama) {
        Criteria c = getSession().createCriteria(getPersistentClass());
        c.add(Restrictions.eq(ACTIVO, Boolean.TRUE));

        c.add(Restrictions.eq("descDiagrama", descDiagrama));

        return c.list();
    }
    
    @Override
	public DiagramaAutobus suscribir(DiagramaAutobus entity) {
		try {
			this.getHibernateTemplate().save(entity);
			getHibernateTemplate().flush();
			updateAsientosVendibles(entity);
			
			return entity;
		} catch (final HibernateException ex) {

			throw convertHibernateAccessException(ex);
		}
	}

    @Override
    public DiagramaAutobus actualizacion(DiagramaAutobus entity) {
		entity = getHibernateTemplate().merge(entity);
		getHibernateTemplate().flush();
		updateAsientosVendibles(entity);
		return entity;
	}
    
	private void updateAsientosVendibles(DiagramaAutobus entity) {
		try{
			StringBuilder qry = new StringBuilder();
			qry.append("UPDATE diagrama_autobus  ");
			qry.append("SET    CANTASIENTOSVENDIBLES = (SELECT Count(DD.detdiagramaautobus_id) ");
			qry.append("                                  FROM   det_diagrama_autobus DD ");
			qry.append("                                  WHERE ");
			qry.append("       DD.diagramaautobus_id = :diagramaautobus_id ");
			qry.append("       AND DD.vendible = 1 ");
			qry.append("       AND DD.activo = 1) "); 
			qry.append("       WHERE diagramaautobus_id = :diagramaautobus_id "); 
			
			Query query = getSession().createSQLQuery(qry.toString());
			query.setShort("diagramaautobus_id", entity.getDiagramaautobusId());
			query.executeUpdate();
		} catch (final Exception ex) {
			throw new RuntimeException("Erro ao atualizar qtd de assentos disponíveis",ex);
		}
	}
}
