#compdef aurinstall aurupdate aurremove

_aurlist_dirs() {
  local -a pkgs
  local AUR_DIR=${AUR_DIR:-$HOME/Aur}

  pkgs=()
  if [[ -d $AUR_DIR ]]; then
    local d
    for d in "$AUR_DIR"/*; do
      [[ -d $d ]] || continue
      pkgs+=("${d:t}")
    done
  fi

  compadd "$pkgs[@]"
}

_aurlist_installed() {
  local -a pkgs
  pkgs=(${(f)"$(pacman -Qm 2>/dev/null | awk '{print $1}')"})
  compadd "$pkgs[@]"
}

_aursearch_online() {
  local cur
  cur="${words[CURRENT]}"

  [[ -z "$cur" || ${#cur} -lt 2 ]] && return 0

  command -v curl >/dev/null 2>&1 || return 0
  command -v jq >/dev/null 2>&1 || return 0

  local -a remote_pkgs
  remote_pkgs=(${(f)"$(
    curl -fsSL "https://aur.archlinux.org/rpc/v5/search/${cur}?by=name" 2>/dev/null \
    | jq -r '.results[].Name' 2>/dev/null
  )"})

  (( ${#remote_pkgs[@]} )) && compadd "$remote_pkgs[@]"
}

_aurinstall() {
  _aurlist_dirs
  _aursearch_online
}

_aurupdate() {
  _message 'aucun argument'
}

_aurremove() {
  _aurlist_installed
}

compdef _aurinstall aurinstall
compdef _aurupdate aurupdate
compdef _aurremove aurremove
