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

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
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.PricingVigenciaDAO;
import com.rjconsultores.ventaboletos.entidad.Pricing;
import com.rjconsultores.ventaboletos.entidad.PricingVigencia;

/**
 * 
 * @author Rafius
 */
@Repository("pricingVigenciaDAO")
public class PricingVigenciaHibernateDAO extends GenericHibernateDAO<PricingVigencia, Integer>
		implements PricingVigenciaDAO {

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

	@Override
	public List<PricingVigencia> obtenerTodos() {
		Criteria c = getSession().createCriteria(getPersistentClass());
		c.add(Restrictions.eq(ACTIVO, Pricing.ATIVO));

		return c.list();
	}

	@Override
	public List<PricingVigencia> buscarPorVigencias(PricingVigencia pv) {
		Criteria c = getSession().createCriteria(getPersistentClass());

		c.add(Restrictions.eq(ACTIVO, Pricing.ATIVO));

		c.add(Restrictions.eq("pricing", pv.getPricing()));

		Date fecinicioventa = pv.getFecinicioventa();
		Date fecfinventa = pv.getFecfinventa();

		c.add(Restrictions.or(Restrictions.between("fecinicioventa", fecinicioventa, fecfinventa),
				(Restrictions.between("fecfinventa", fecinicioventa, fecfinventa))));

		return c.list();
	}

	@Override
	public Boolean podeSalvar(Pricing pricing, PricingVigencia pricingVigencia, Date inicio, Date fim) {
		Calendar fecInicio = Calendar.getInstance();
		fecInicio.setTime(inicio);
		fecInicio.set(Calendar.MILLISECOND, 0);
		fecInicio.set(Calendar.SECOND, 0);

		Calendar fecFin = Calendar.getInstance();
		fecFin.setTime(fim);
		fecFin.set(Calendar.MILLISECOND, 0);
		fecFin.set(Calendar.SECOND, 0);

		Criteria c = this.getSession().createCriteria(PricingVigencia.class);
		c.add(Restrictions.eq(ACTIVO, Pricing.ATIVO));
		c.add(Restrictions.ge("fecfinviaje", fecInicio.getTime()));
		c.add(Restrictions.le("fecinicioviaje", fecFin.getTime()));
		c.add(Restrictions.eq("pricing", pricing));
		if (pricingVigencia.getPricingvigenciaId() != null) {
			c.add(Restrictions.ne("pricingvigenciaId", pricingVigencia.getPricingvigenciaId()));
		}

		return c.list().isEmpty();
	}
}
