package br.com.centralit.citcorpore.ajaxForms;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citcorpore.bean.AutoCompleteDTO;
import br.com.centralit.citcorpore.bean.ModeloEmailDTO;
import br.com.centralit.citcorpore.negocio.ModeloEmailService;
import br.com.citframework.service.ServiceLocator;

@SuppressWarnings("rawtypes")
public class AutoCompleteModelosEmails extends AjaxFormAction {

	@Override
	@SuppressWarnings("unchecked")
	public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String consulta = request.getParameter("query");
		ModeloEmailService modeloEmailService = (ModeloEmailService) ServiceLocator.getInstance()
				.getService(ModeloEmailService.class, null);

		Collection<ModeloEmailDTO> modeloEmail = new ArrayList<ModeloEmailDTO>();
		modeloEmail = modeloEmailService.consultarModelosEmailPorTitulo(consulta);

		AutoCompleteDTO autoCompleteDTO = new AutoCompleteDTO();
		Gson gson = new Gson();
		List lst = new ArrayList();
		List lstVal = new ArrayList();

		if (modeloEmail != null && !modeloEmail.isEmpty() && modeloEmail.size() > 0) {
			for (ModeloEmailDTO modelosEmail : modeloEmail) {
				lst.add(modelosEmail.getTitulo());
				lstVal.add(modelosEmail.getIdModeloEmail());
			}
		}

		autoCompleteDTO.setQuery(consulta);
		autoCompleteDTO.setSuggestions(lst);
		autoCompleteDTO.setData(lstVal);

		String json = gson.toJson(autoCompleteDTO);
		request.setAttribute("json_response", json);
	}

	@Override
	public Class<AutoCompleteModelosEmails> getBeanClass() {
		return AutoCompleteModelosEmails.class;
	}

}
