package com.rjconsultores.ventaboletos.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.SessionFactory;
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.OrgaoTramoDAO;
import com.rjconsultores.ventaboletos.entidad.OrgaoTramo;

@Repository("orgaoTramoDAO")
public class OrgaoTramoHibernateDAO extends GenericHibernateDAO<OrgaoTramo, Integer> implements OrgaoTramoDAO {

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

	@Override
	public OrgaoTramo buscar(Integer origenId, Integer destinoId, Integer viaId, Integer orgaoConcedenteId, Integer claseServicioId) {
		Criteria c = makeCriteria();
		Criteria cTramo = c.createCriteria("tramo");
		cTramo.add(Restrictions.eq("origem.paradaId", origenId));
		cTramo.add(Restrictions.eq("destino.paradaId", destinoId));
		cTramo.add(Restrictions.eq("via.viaId", viaId));
		cTramo.add(Restrictions.eq(ACTIVO, Boolean.TRUE));

		c.add(Restrictions.eq("orgaoConcedente.orgaoConcedenteId", orgaoConcedenteId));
		c.add(Restrictions.eq("claseServicio.claseservicioId", claseServicioId));
		c.add(Restrictions.eq(ACTIVO, Boolean.TRUE));
		
		c.setFetchMode("tramo", FetchMode.SELECT);

		List<OrgaoTramo> list = c.list();

		if (list.size() > 1) {
			throw new RuntimeException("Erro ao consultar os dados do coeficiente por trecho. Retornou mais de um resultado");
		}

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}
	
	
}
