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.SmartReportDTO;
import br.com.centralit.citcorpore.negocio.SmartReportService;
import br.com.citframework.service.ServiceLocator;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class AutoCompleteSmartReport extends AjaxFormAction {
	@Override
	public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String consulta = request.getParameter("query");
		
		SmartReportService smartReportService = (SmartReportService) ServiceLocator.getInstance().getService(SmartReportService.class, null);
		
		Collection<SmartReportDTO> smartReportDTOs = new ArrayList<SmartReportDTO>();
		smartReportDTOs = smartReportService.findByIdentificacao(consulta);
		
		AutoCompleteDTO autoCompleteDTO = new AutoCompleteDTO();
		Gson gson = new Gson();
		List lst = new ArrayList();
		List lstVal = new ArrayList();

		if (smartReportDTOs != null && !smartReportDTOs.isEmpty()) {
			for (SmartReportDTO smartReportDTO : smartReportDTOs) {
				lst.add(smartReportDTO.getIdentificacao());
				lstVal.add(smartReportDTO.getIdSmartReport() + "|" + smartReportDTO.getIdCategoria());
			}
		}

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

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

	@Override
	public Class getBeanClass() {
		return SmartReportDTO.class;
	}

}
