package com.rjconsultores.ventaboletos.dao.hibernate;

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

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.rjconsultores.ventaboletos.dao.ComissaoReceitaDAO;
import com.rjconsultores.ventaboletos.entidad.ComissaoReceita;
import com.rjconsultores.ventaboletos.utilerias.DateUtil;

@Repository("comissaoReceitaHibernateDAO")
public class ComissaoReceitaHibernateDAO extends GenericHibernateDAO<ComissaoReceita, Integer> implements ComissaoReceitaDAO {
	
	@Autowired
	public ComissaoReceitaHibernateDAO(@Qualifier("sessionFactory") SessionFactory factory) {
		setSessionFactory(factory);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<ComissaoReceita> recuperarComissaoReceita(Integer empresaId, Integer puntoVentaId, Date dataInicial, Date dataFinal) {
		StringBuilder hql = new StringBuilder();
		hql.append("select c from ComissaoReceita c ")
		   .append("where c.activo = 1 ")
		   .append("  AND c.puntoVenta.puntoventaId = :puntoventaId ")
		   .append("  AND c.empresa.empresaId = :empresaId ")
		   .append("  AND c.datamovimento between TO_DATE(:dataInicial,'DD/MM/YYYY') and TO_DATE(:dataFinal,'DD/MM/YYYY') ")
		   .append("order by c.empresa.nombempresa, c.puntoVenta.nombpuntoventa, c.datamovimento");

		Query query = getSession().createQuery(hql.toString());
		query.setString("dataInicial", DateUtil.getStringDate(dataInicial, "dd/MM/yyyy"));
		query.setString("dataFinal", DateUtil.getStringDate(dataFinal, "dd/MM/yyyy"));
		query.setInteger("puntoventaId", puntoVentaId);
		query.setInteger("empresaId", empresaId);

		return query.list();
	}

	@Override
	public void limparComissaoReceita(Integer empresaId, Integer puntoVentaId, Date dataInicial, Date dataFinal) {
		StringBuilder hql = new StringBuilder();
		hql.append("delete comissao_receita ");
		hql.append("where activo = 1 ");
		hql.append("  AND puntoventa_id = :puntoventaId ");
		hql.append("  AND empresa_id = :empresaId ");
		hql.append("  AND datamovimento between TO_DATE(:dataInicial,'DD/MM/YYYY hh24:mi') and TO_DATE(:dataFinal,'DD/MM/YYYY hh24:mi') ");

		Query query = getSession().createSQLQuery(hql.toString());
		query.setString("dataInicial", DateUtil.getStringDate(DateUtil.inicioFecha(dataInicial), "dd/MM/yyyy HH:mm"));
		query.setString("dataFinal", DateUtil.getStringDate(DateUtil.inicioFecha(dataFinal), "dd/MM/yyyy HH:mm"));
		query.setInteger("puntoventaId", puntoVentaId);
		query.setInteger("empresaId", empresaId);
		
		query.executeUpdate();
	}
	
}
