package com.rjconsultores.ventaboletos.dao.hibernate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
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_PricingDiaDAO;
import com.rjconsultores.ventaboletos.entidad.GP_Pricing;
import com.rjconsultores.ventaboletos.entidad.GP_PricingDia;
import com.rjconsultores.ventaboletos.entidad.Pricing;

@Repository("gp_pricingDiaDAO")
public class GP_PricingDiaHibernateDAO extends GenericHibernateDAO<GP_PricingDia, Integer>
		implements GP_PricingDiaDAO {

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

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

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

		return c.list();
	}

	public List<GP_PricingDia> buscarTraslapa(GP_PricingDia pricingDia) {
		Date horarioinicio = pricingDia.getHorarioinicio();
		Date horariofin = pricingDia.getHorariofin();

		SimpleDateFormat sf = new SimpleDateFormat("HHmm");

		StringBuilder hql = new StringBuilder();
		hql.append("select pv from GP_PricingDia pv ");
		hql.append(" where pv.activo = 1 ");
		hql.append(" and pricing.pricingId = ").append(pricingDia.getPricing().getPricingId());
		hql.append(" and pv.horariofin >= :horariofin ");
		hql.append(" and pv.horarioinicio >= :horarioinicio ");

		log.info("Hora Ini: " + sf.format(horarioinicio));
		log.info("Hora Fin: " + sf.format(horariofin));
		log.info("SQL: " + hql.toString());

		Query sq = getSession().createQuery(hql.toString());
		sq.setParameter("horariofin", horariofin);
		sq.setParameter("horarioinicio", horarioinicio);

		return sq.list();
	}

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

		return c.list();
	}
}
