package br.mp.mprj.portal.portlet.gestaomensagens.search;

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

import javax.portlet.PortletRequest;

import br.mp.mprj.portal.portlet.gestaomensagens.search.indexer.TemplateIndexer;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.Template;
import br.mp.mprj.portal.portlet.gestaomensagens.service.service.TemplateLocalServiceUtil;
import br.mp.mprj.portal.portlet.gestaomensagens.util.GestaoMensagensUtil;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.search.BooleanClauseOccur;
import com.liferay.portal.kernel.search.BooleanQuery;
import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
import com.liferay.portal.kernel.search.Document;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.search.Hits;
import com.liferay.portal.kernel.search.ParseException;
import com.liferay.portal.kernel.search.SearchContext;
import com.liferay.portal.kernel.search.SearchContextFactory;
import com.liferay.portal.kernel.search.SearchEngineUtil;
import com.liferay.portal.kernel.search.SearchException;
import com.liferay.portal.kernel.search.Sort;
import com.liferay.portal.kernel.search.SortFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;

public class TemplateSearch {

	private static final Sort[] SORT_PADRAO = {SortFactoryUtil.create("nome_sortable", false)};
	
	public static List<Template> pesquisar(PortletRequest req) 
			throws ParseException, SearchException {
		List<Template> list = new ArrayList<Template>();
		
		String nome = ParamUtil.getString(req, "nomeTemplateSearch");
		
		SearchContext sc = SearchContextFactory.getInstance(PortalUtil.getHttpServletRequest(req));
		
		sc.setAndSearch(true);
		sc.setEntryClassNames(TemplateIndexer.CLASS_NAMES);
		sc.setSorts(SORT_PADRAO);
		
		BooleanQuery query = BooleanQueryFactoryUtil.create(sc);
		
		ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY);

		long groupId = themeDisplay.getScopeGroupId();
		String groupIdStr = String.valueOf(groupId);
		
		//utilizar desta definicao para, criando outro BooleanQuery para aplicar o BooleanClauseOccur, 
		//evitar resultados incorretos ao utilizar BooleanQuery.
		BooleanQuery bqEntryClassName = BooleanQueryFactoryUtil.create(sc);
		bqEntryClassName.addExactTerm(Field.ENTRY_CLASS_NAME, Template.class.getName());
		
		//forcar que o entryClassName seja obrigatorio na query gerada pela API, 
		//para evitar resultados incorretos de outras entidades.
		query.add(bqEntryClassName, BooleanClauseOccur.MUST);
		
		if (Validator.isNotNull(nome)) {
			//sc.setKeywords(nome);
			query.addExactTerm("+nome", nome);
		}
		//TODO 1 alterar 1 para true
		query.addTerm("ativo", "true", true, BooleanClauseOccur.MUST);
		query.addTerm("+groupId",groupIdStr ,  true);
		
		boolean doAgain = false;
		do {
			Hits hits = SearchEngineUtil.search(sc, query);
			
			//fazer o parse dos resultados
			for (Document doc : hits.getDocs()) {
				try {
					list.add(TemplateLocalServiceUtil.getTemplate(GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK))));
					if (list.size() > 0) {
						for (Template template : list) {
							doAgain = template.getNome().contains("removed-");
						}
					}
				}
				catch (PortalException|SystemException ex) {
					GestaoMensagensUtil.descartarRascunhos(req);
					throw new SearchException(ex);
				}
			}
		} while (doAgain);
		
	/*	try {
			MensagemLocalServiceUtil.enviaMensagem("Meu primeiro e-mail por servico", 
					"<HTM>><BODY><<P> Meu primeiro e-mail enviado por serviço.</P></BODY></HTML>", 
					"Bianca Passos", 102207, 108006, 1, "107912", 29601, 20182, 20155);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		return list;
	}
	
}
