Optional<DecisionListSupport> dlsOp = findCompletionDecision(cqlQuery);
if (!dlsOp.isPresent()) {
// user started typing, has first world and there is no decision
// list for it
ContextCqlCompletion initial = null;
if (!cqlQuery.partLc.isEmpty() && !cqlQuery.partLc.contains(" ")) {
initial = new ContextCqlCompletion(CqlQueryType.UNKNOWN, initialCqlCompletion);
}
return Optional.ofNullable(initial);
}
if (cursorPosition < 0) {
cursorPosition = 0;
}
DecisionListSupport dls = dlsOp.get();
CqlPartCompletion[][] decisionList = dls.getDecisionList();
if (decisionList.length == 0) {
return Optional.empty();
}
int cqLength = cqlQuery.partLc.length();
if (cursorPosition > cqLength) {
cursorPosition = cqLength;
}
String cqlLc = cqlQuery.partLc.substring(0, cursorPosition);
int offset = 0;
CqlPartCompletion lastMatchingCompletion = null;
// go over all parsing decisions, until you find one that cannot be
// applied - this means that previous one
// is the right chose for completion
for (CqlPartCompletion[] partCompletionList : decisionList) {
LOG.debug("Next completion");
boolean found = false;
for (CqlPartCompletion partCompletion : partCompletionList) {
LOG.debug("Checking: {}", partCompletion);
int completionStartMarker = -1;
if (partCompletion instanceof MarkerBasedCompletion) {
MarkerBasedCompletion partStatic = (MarkerBasedCompletion) partCompletion;
String startMarker = partStatic.startMarker().partLc;
completionStartMarker = cqlLc.indexOf(startMarker, offset);
} else if (partCompletion instanceof OffsetBasedCompletion) {
OffsetBasedCompletion partDynamic = (OffsetBasedCompletion) partCompletion;
completionStartMarker = partDynamic.canApply(cqlQuery, offset);
} else {
throw new ServiceException("Unsupported CqlPartCompletion: " + partCompletion.getClass());
}
LOG.debug("completionStartMarker: {}", completionStartMarker);
if (completionStartMarker == -1) {
// this decision cannot be applied - try next one
continue;
}
found = true;
// current decision can be applied - try next one
offset = completionStartMarker + 1;
lastMatchingCompletion = partCompletion;
}
if (!found) {
break;
}
}
ContextCqlCompletion cqc = null;
if (lastMatchingCompletion != null) {
CqlCompletion cqlCompletion = lastMatchingCompletion.getCompletion(cqlQuery);
cqc = new ContextCqlCompletion(dls.queryName(), cqlCompletion);
LOG.debug("Completion found: {}", cqc);
} else {
LOG.debug("Completion not found");
}