#compdef polybar
#
# Completion for polybar (https://github.com/polybar/polybar)
#   jaagr <c@rlberg.se>
#
_polybar() {
  local L='-l --log'
  local Q='-q --quiet'
  local C='-c --config'
  local R='-r --reload'
  local D='-d --dump'
  local M='-m --list-monitors'
  local MM='-M --list-all-monitors'
  local W='-w --print-wmname'
  local S='-s --stdout'

  _arguments -n : \
    '(-)'{-h,--help}'[Display help text and exit]' \
    '(-)'{-v,--version}'[Display build details and exit]' \
    "($L $Q)"{-l,--log=}'[Set the logging verbosity (default: notice)]:verbosity level:(error warning notice info trace)' \
    "($L $Q)"{-q,--quiet}'[Be quiet (will override -l)]' \
    "($C)"{-c,--config=}'[Path to the configuration file]:configuration file:_files' \
    "($R)"{-r,--reload}'[Reload when the configuration has been modified]' \
    "($D $R $M $W $S)"{-d,--dump=}'[Print parameter value in bar section and exit]:parameter name' \
    "($MM $M $D $R $W $S)"{-m,--list-monitors}'[Print list of available monitors (Excluding cloned monitors) and exit]' \
    "($MM $M $D $R $W $S)"{-M,--list-all-monitors}'[Print list of all available monitors (Including cloned monitors) and exit]' \
    "($W $R $D $M $S)"{-w,--print-wmname}'[Print the generated WM_NAME and exit]' \
    "($S)"{-s,--stdout}'[Output data to stdout instead of drawing the X window]' \
    '::bar name:_polybar_list_names'
}

(( $+functions[_polybar_default_file] )) || _polybar_default_file() {
  local suffix=/polybar/config.ini

  local home_path=${XDG_CONFIG_HOME:-$HOME/.config}${suffix}
  local etc_xdg_path=${XDG_CONFIG_DIRS:-/etc/xdg}${suffix}
  local etc_path=/etc${suffix}

  if [ -r "$home_path" ]; then
    echo "$home_path"
  elif [ -r "$etc_xdg_path" ]; then
    echo "$etc_xdg_path"
  elif [ -r "$etc_path" ]; then
    echo "$etc_path"
  fi
}

(( $+functions[_polybar_list_names] )) || _polybar_list_names() {
  local conf
  if (( $+opt_args[-c] )); then
    conf=${(e)opt_args[-c]}
  elif (( $+opt_args[--config] )); then
    conf=${(e)opt_args[--config]}
  else
    conf=$(_polybar_default_file)
  fi
  local names; names=(${(f)"$(sed -nE 's|[[:space:]]*\[bar/([^\]+)\][[:space:]]*$|\1|p' ${conf} 2>/dev/null)"})
  _describe -t names 'configuration name' names
}

_polybar "$@"