#!/usr/bin/bash

_sdk() {
	local -r before_previous_word="${COMP_WORDS[COMP_CWORD - 2]}"
	local -r previous_word="${COMP_WORDS[COMP_CWORD - 1]}"
	local -r current_word="${COMP_WORDS[COMP_CWORD]}"

	if ((COMP_CWORD == 3)); then
		__sdkman_complete_candidate_version "$before_previous_word" "$previous_word" "$current_word"

		return
	fi

	__sdkman_complete_command "$previous_word" "$current_word"
}

__sdkman_complete_command() {
	local -r command=$1
	local -r current_word=$2

	local candidates

	case $command in
		sdk)
			candidates=("install" "uninstall" "list" "use" "config" "default" "home" "env" "current" "upgrade" "version" "broadcast" "help" "offline" "selfupdate" "update" "flush")
			;;
		current|default|home|uninstall|upgrade|use)
			local -r candidate_paths=("${SDKMAN_CANDIDATES_DIR}"/*)

			for candidate_path in "${candidate_paths[@]}"; do
				candidates+=(${candidate_path##*/})				
			done
			;;
		install|list)
		    curl --silent "${SDKMAN_CANDIDATES_API}/candidates/all" | \
			while IFS= read -d, -r candidate; do
				candidates+=($candidate)
			done
			;;
		env)
			candidates=("init install clear")
			;;
		offline)
			candidates=("enable" "disable")
			;;
		selfupdate)
			candidates=("force")
			;;
		flush)
			candidates=("archives" "temp" "broadcast" "version")
			;;
	esac

	COMPREPLY=($(compgen -W "${candidates[*]}" -- "$current_word"))
}

__sdkman_complete_candidate_version() {
	local -r command=$1
	local -r candidate=$2
	local -r candidate_version=$3

	local candidates

	case $command in
		use|default|home|uninstall)
			local -r version_paths=("${SDKMAN_CANDIDATES_DIR}/${candidate}"/*)

			for version_path in "${version_paths[@]}"; do
				[[ $version_path = *current ]] && continue

				candidates+=(${version_path##*/})
			done
			;;
		install)
		    curl --silent "${SDKMAN_CANDIDATES_API}/candidates/$candidate/${SDKMAN_PLATFORM}/versions/all" | \
			while IFS= read -d, -r version; do
				candidates+=($version)
			done
			;;
	esac

	COMPREPLY=($(compgen -W "${candidates[*]}" -- "$candidate_version"))
}

complete -o default -F _sdk sdk

# Set 'sdkman_auto_complete' to 'true' in .sdkman/etc/config to enable completion

