#!/bin/sh
# Use picocli-shell-jline2's completer with the jline2 library.
set -eu

srcdir=$(pwd)
tmp=${AUTOPKGTEST_TMP:-$(mktemp -d)}
cd "$tmp"

CP=/usr/share/java/picocli.jar:/usr/share/java/picocli-shell-jline2.jar:/usr/share/java/jline2.jar

cat > Complete.java <<'EOF'
import java.util.ArrayList;
import java.util.List;

import jline.console.completer.Completer;
import picocli.CommandLine;
import picocli.shell.jline2.PicocliJLineCompleter;

public class Complete {
    public static void main(String[] args) {
        Completer completer = new PicocliJLineCompleter(new CommandLine(new Greet()).getCommandSpec());
        String buffer = args[0];
        List<CharSequence> candidates = new ArrayList<CharSequence>();
        completer.complete(buffer, buffer.length(), candidates);
        for (CharSequence candidate : candidates) {
            System.out.println(candidate);
        }
    }
}
EOF

mkdir classes
javac -cp "$CP" -d classes "$srcdir/debian/tests/Greet.java" Complete.java 2>&1

check() {
    # check <buffer> <expected candidate>
    out=$(java -cp "$CP:classes" Complete "$1")
    if printf '%s\n' "$out" | grep -qx -e "$2"; then
        echo "ok: '$1' completes with '$2'"
    else
        echo "FAIL: '$1' did not offer '$2'; candidates were:"
        printf '%s\n' "$out"
        exit 1
    fi
}

# picocli returns the remaining characters of each matching candidate
check "--na" "me"
check "--" "count"
check "he" "lp"
