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.GP_PricingVigenciaDAO;
import com.rjconsultores.ventaboletos.entidad.GP_Pricing;
import com.rjconsultores.ventaboletos.entidad.GP_PricingVigencia;

@Repository("gp_pricingVigenciaDAO")
public class GP_PricingVigenciaHibernateDAO extends GenericHibernateDAO<GP_PricingVigencia, Integer>
		implements GP_PricingVigenciaDAO {

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

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

		return c.list();
	}

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

		c.add(Restrictions.eq(ACTIVO, GP_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(GP_Pricing pricing, GP_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(GP_PricingVigencia.class);
		c.add(Restrictions.eq(ACTIVO, GP_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();
	}

	@Override
	public List<GP_PricingVigencia> obtenerTodoPorPricing(GP_Pricing pricing) {
		Criteria c = getSession().createCriteria(getPersistentClass());
		c.add(Restrictions.eq("pricing.pricingId", pricing.getPricingId()));

		return c.list();
	}
}
