package com.rjconsultores.ventaboletos.dao.hibernate;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.OCDDAO;
import com.rjconsultores.ventaboletos.entidad.OCD;
import com.rjconsultores.ventaboletos.vo.reembolsoocdnotacredito.ReembolsoOcdNotaCreditoVO;

@Repository("ocdHibernateDAO")
public class OCDHibernateDAO extends GenericHibernateDAO<OCD, Integer>
		implements OCDDAO {

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

	@SuppressWarnings("unchecked")
	@Override
	public List<ReembolsoOcdNotaCreditoVO> busquedaDatosReembolsoOcdNotaCreditoRS(Date fecInicial, Date fecFinal, Date fecPagamentoInicial, Date fecPagamentoFinal, Boolean indPago) {
		
		Map<String, Object> params = new HashMap<String,Object>();
		String queryString = "SELECT o FROM OCD o "
				+ "LEFT JOIN FETCH o.boleto b "
				+ "LEFT JOIN FETCH o.ocdDatosPagamentos "
				+ "WHERE 1=1 ";
		
		if (fecInicial != null) {
			queryString += "AND o.fecinc >= :fecInicial ";
			params.put("fecInicial", fecInicial);
		}
		if (fecFinal != null) {
			queryString += "AND o.fecinc <= :fecFinal ";
			params.put("fecFinal", fecFinal);
		}
		
		if (fecPagamentoInicial != null) {
			queryString += "AND o.fecpagar >= :fecPagamentoInicial ";
			params.put("fecPagamentoInicial", fecPagamentoInicial);
		}
		if (fecPagamentoFinal != null) {
			queryString += "AND o.fecpagar <= :fecPagamentoFinal ";
			params.put("fecPagamentoFinal", fecPagamentoFinal);
		}
		
		if (indPago != null) {
			queryString += "AND o.indpago = :indPago ";
			params.put("indPago", indPago);
		}
		
		Query query = getSession().createQuery(queryString);
		for (String p : query.getNamedParameters()) {
			query.setParameter(p, params.get(p));
	    }
		
		List<OCD> listOcd = query.list();
		List<ReembolsoOcdNotaCreditoVO> result = new ArrayList<ReembolsoOcdNotaCreditoVO>();
		for (OCD ocd : listOcd) {
			ReembolsoOcdNotaCreditoVO vo = ReembolsoOcdNotaCreditoVO.builder().ocd(ocd)
					.boleto(ocd.getBoleto()).datosPagamento(ocd.getOcdDatosPagamentos()).build();
			result.add(vo);
		}
		
		return result;
		
	}

}
