package com.rjconsultores.ventaboletos.dao.hibernate;

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

import org.apache.commons.lang.StringUtils;
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.ClientePacoteDAO;
import com.rjconsultores.ventaboletos.entidad.ClientePacote;
import com.rjconsultores.ventaboletos.vo.busquedapacotes.ClientePacoteVO;

@Repository("clientePacoteDAO")
public class ClientePacoteHibernateDAO extends GenericHibernateDAO<ClientePacote, Long> implements ClientePacoteDAO {
	
	@Autowired
	public ClientePacoteHibernateDAO(@Qualifier("sessionFactory") SessionFactory factory) {
		setSessionFactory(factory);
	}

	@Override
	public List<ClientePacoteVO> busquedaDatosClientePacote(String cpfCnpj) {
		List<ClientePacoteVO> clientePacoteVOs = new ArrayList<ClientePacoteVO>();
		if(StringUtils.isNotBlank(cpfCnpj)) {
			Map<String, Object> parametros = new HashMap<String, Object>();
			StringBuilder sQuery = new StringBuilder();
			sQuery.append("SELECT DISTINCT NEW com.rjconsultores.ventaboletos.vo.busquedapacotes.ClientePacoteVO(cp.razaoSocial, cp.cpfCnpj, cp.tipoPessoa, cp.descemail, cp.desctelefone, cp.descfax, cp.cep, ")
				  .append("cp.endereco, cp.numero, cp.complemento, cp.pais, cp.estado, cp.cidade, cp.bairro) ")
				  .append("FROM ClientePacote cp ");
			
			if(StringUtils.isNotBlank(cpfCnpj)) {
				sQuery.append("WHERE cp.cpfCnpj = :cpfCnpj ");
				parametros.put("cpfCnpj", cpfCnpj.replaceAll("[^0-9]", ""));
			}
			
			sQuery.append("ORDER BY cp.razaoSocial ");
			Query qr = getSession().createQuery(sQuery.toString());
			for (Entry<String, Object> parametro : parametros.entrySet()) {
				qr.setParameter(parametro.getKey(), parametro.getValue());
			}
			
			clientePacoteVOs = qr.list();
		}
		
		return clientePacoteVOs;
	}

}
