#!/bin/bash
#shellcheck disable=SC2155,SC2207,SC2309,SC2034,SC2154,SC1087
set -eo pipefail

_notes_completion() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local command="${COMP_WORDS[1]}"

    if [[ COMP_CWORD -eq 1 ]]; then
        COMPREPLY=($(compgen -W "add edit rm list" -- "$cur"))
        return
    fi

    if [[ "$command" == "edit" || "$command" == "rm" ]]; then
        local notes_dir="$HOME/notes"
        local notes=()
        if [[ -d "$notes_dir" ]]; then
            for file in "$notes_dir"/*.md; do
                if [[ -f "$file" ]]; then
                    notes+=("$(basename "$file")")
                fi
            done
        fi
        local IFS=$'\n'
        COMPREPLY=($(compgen -W "$(printf '%s\n' "${notes[@]}")" -- "$cur"))
        compopt -o filenames
        return
    fi
}

_notes() {
    local -a commands=(
        'add:Create a new note'
        'edit:Open a note in editor'
        'rm:Remove a note'
        'list:List all notes'
    )

    if (( CURRENT == 2 )); then
        _describe 'command' commands
    elif (( CURRENT >= 3 )); then
        case $words[2] in
            edit|rm)
                local notes_dir="$HOME/notes"
                if [[ -d "$notes_dir" ]]; then
                    _files -W "$notes_dir" -g '*.md'
                fi
                ;;
            *)
                _message 'no more arguments'
                ;;
        esac
    fi
}

if [[ -n "$BASH_VERSION" ]]; then
    complete -F _notes_completion notes ./notes
fi

if [[ -n "$ZSH_VERSION" ]]; then
    compdef _notes notes ./notes
fi
