#!/bin/sh
# Use picocli-shell-jline3's completer and command registry with jline3.
set -eu

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

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

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

import org.jline.reader.Candidate;
import org.jline.reader.impl.DefaultParser;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.shell.jline3.PicocliCommands;
import picocli.shell.jline3.PicocliJLineCompleter;

@Command(name = "shell", subcommands = Greet.class)
public class Shell implements Runnable {
    public void run() {
    }

    public static void main(String[] args) throws Exception {
        if (args[0].equals("complete")) {
            String buffer = args[1];
            PicocliJLineCompleter completer =
                    new PicocliJLineCompleter(new CommandLine(new Greet()).getCommandSpec());
            List<Candidate> candidates = new ArrayList<Candidate>();
            completer.complete(null, new DefaultParser().parse(buffer, buffer.length()), candidates);
            for (Candidate candidate : candidates) {
                System.out.println(candidate.value());
            }
        } else if (args[0].equals("registry")) {
            PicocliCommands commands = new PicocliCommands(new CommandLine(new Shell()));
            System.out.println("names: " + commands.commandNames());
            System.out.println("hasCommand: " + commands.hasCommand("greet"));
            for (String line : commands.commandInfo("greet")) {
                System.out.println("info: " + line);
            }
            commands.invoke(null, "greet", "--name", "JLine3");
        }
    }
}
EOF

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

check() {
    # check <buffer> <expected candidate>
    out=$(java -cp "$RUN_CP" Shell 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
}

# For jline3, picocli returns all candidate words and leaves filtering by
# prefix to the jline3 LineReader.
check "--na" "--name"
check "--" "--count"
check "he" "help"

java -cp "$RUN_CP" Shell registry > out.txt
for pattern in '^names: \[greet\]$' '^hasCommand: true$' '^info: Says hello\.$' '^Hello, JLine3!$'; do
    if grep -q -e "$pattern" out.txt; then
        echo "ok: PicocliCommands: $pattern"
    else
        echo "FAIL: PicocliCommands: '$pattern' not found in:"
        cat out.txt
        exit 1
    fi
done
