package completion

// bashScript is the bash completion shim emitted by `mlr completion bash`. It
// holds no knowledge of Miller's grammar: it forwards the current words to
// `mlr completion complete`, which returns a one-line directive followed by
// candidate words.
const bashScript = `# bash completion for mlr -- generated by 'mlr completion bash'
_mlr_complete() {
    local cur response directive rest
    cur="${COMP_WORDS[COMP_CWORD]}"
    response=$("${COMP_WORDS[0]}" completion complete "$COMP_CWORD" "${COMP_WORDS[@]}" 2>/dev/null)

    # The first line is a directive; the remaining lines are candidate words.
    # We split with parameter expansion rather than array slicing
    # (${arr[@]:1}), which is broken in the bash 3.2 that ships with macOS.
    directive=${response%%$'\n'*}
    if [[ "$response" == *$'\n'* ]]; then
        rest=${response#*$'\n'}
    else
        rest=""
    fi

    # compgen -f rather than 'compopt -o default' for file completion, since
    # compopt does not exist in bash 3.2.
    local IFS=$'\n'
    COMPREPLY=()
    case "$directive" in
        files)
            COMPREPLY=( $(compgen -f -- "$cur") )
            compopt -o filenames 2>/dev/null
            ;;
        default)
            COMPREPLY=( $rest $(compgen -f -- "$cur") )
            compopt -o filenames 2>/dev/null
            ;;
        *)
            COMPREPLY=( $rest )
            ;;
    esac
}
complete -F _mlr_complete mlr
`

// zshScript is the zsh completion shim emitted by `mlr completion zsh`.
const zshScript = `#compdef mlr
# zsh completion for mlr -- generated by 'mlr completion zsh'

# Initialize the completion system if it has not been already; this provides
# 'compdef' and makes 'source <(mlr completion zsh)' work even when the user's
# zsh startup files do not run compinit themselves.
if ! (( $+functions[compdef] )); then
    autoload -Uz compinit && compinit
fi

_mlr() {
    local -a response candidates
    local directive
    response=("${(@f)$(${words[1]} completion complete $((CURRENT-1)) "${words[@]}" 2>/dev/null)}")

    directive=${response[1]}
    candidates=(${response[2,-1]})

    case $directive in
        files)
            _files
            ;;
        default)
            (( ${#candidates} )) && compadd -- ${candidates}
            _files
            ;;
        *)
            compadd -- ${candidates}
            ;;
    esac
}
compdef _mlr mlr
`
