package to.etc.domuidemo.pages.special.ace;

import to.etc.domui.component.ace.AceEditor;
import to.etc.domui.component.ace.AceEditor.Completion;
import to.etc.domui.component.layout.ButtonBar;
import to.etc.domui.component.misc.MsgBox;
import to.etc.domui.dom.html.UrlPage;
import to.etc.util.FileTool;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a>
 * Created on 23-12-17.
 */
public class AcePage extends UrlPage {
	@Override public void createContent() throws Exception {
		AceEditor.initialize(this);

		AceEditor editor = new AceEditor();
		editor.setMode("ace/mode/pgsql");
		editor.setTheme("ace/theme/iplastic");
		editor.setHeight("200px");
		editor.setWidth("600px");
		add(editor);

		String text = FileTool.readResourceAsString(getClass(), "demojs.js", "utf-8");
		editor.setValue(text);

		editor.setCompletionHandler(this::completeCode);


		ButtonBar bb = new ButtonBar();
		add(bb);
		bb.addButton("SetText", a -> {
			String t2 = FileTool.readResourceAsString(getClass(), "demo2js.js", "utf-8");
			editor.setValue(t2);
		});

		bb.addButton("Clear", a -> editor.setValue(null));

		bb.addButton("Toggle RO", a -> editor.setReadOnly(! editor.isReadOnly()));

		bb.addButton("Show Val", a -> MsgBox.info(this, editor.getValue()));
	}

	private List<Completion> completeCode(String text, int row, int col, String prefix) {
		String[] split = text.split("\\W+");				// All words in the document
		Set<String> set = Arrays.asList(split)
			.stream()
			.map(a -> a.toLowerCase())
			.collect(Collectors.toSet());

		//-- Now find all words starting with prefix
		return set.stream()
			.filter(a -> a.toLowerCase().contains(prefix))
			.map(a -> new Completion(a, a, "Word", 10))
			.collect(Collectors.toList())
			;
	}
}

@@ -323,16 +323,42 @@
 Arrays;%0A
+import java.util.HashSet;%0A
 import j
@@ -1572,16 +1572,30 @@
 %3E set = 
+new HashSet%3C%3E(
 Arrays.a
@@ -1610,141 +1610,125 @@
 lit)
-%0A%09%09%09.stream()%0A%09%09%09.map(a -%3E a.toLowerCase())%0A%09%09%09.collect(Collectors.toSet());%0A%0A%09%09//-- Now find all words starting with prefix%0A%09%09return
+);%0A%0A%09%09//-- Now find all words starting with prefix%0A%09%09String prefixLC = prefix.toLowerCase();%0A%09%09List%3CCompletion%3E res =
  set
@@ -1784,16 +1784,18 @@
 s(prefix
+LC
 ))%0A%09%09%09.m
@@ -1868,16 +1868,86 @@
 oList())
+;%0A%09%09//res.forEach(a -%3E System.out.println(a.getName()));%0A%0A%09%09return res
 %0A%09%09%09;%0A%09%7D

Fix code completion example.