#compdef zrgf

autoload -U is-at-least

function _zrgf() {
  local curcontext="$curcontext" no='!'
  local -a context line state state_descr
  local -A opt_args
  local -a arguments _arguments_options
  integer ret=1

  if is-at-least 5.2; then
      _arguments_options=(-s -S)
  else
      _arguments_options=(-s)
  fi

  zrgf_types=(
    {f,file}'\:"regular files"'
    {d,directory}'\:"directories"'
    {l,symlink}'\:"symbolic links"'
    {e,empty}'\:"empty files or directories"'
    {x,executable}'\:"executable (files)"'
    {s,socket}'\:"sockets"'
    {p,pipe}'\:"named pipes (FIFOs)"'
  )

  arguments=(
    {-x,--show-error}"[general: show errors]"
    {-?,--debug}"[general: show debugging]"
    {-/,--cd}"[general: cd instead of edit]"
    {-1,--print}"[general: print output]"
    {-X,--execute}"[general: execute]"

    {-m,--multi}"[fzf: multi select]"
    {-P,--no-preview}"[fzf: no preview]"
    {-Z,--preview-size=}"[fzf: preview size]:size:"
    {-w,--with-nth=}"[fzf: with nth]:nth:"
    {-h,--height=}"[fzf: height]:height:"
    "--delimiter=[fzf: delimiter]:delim:"
    '*'{-b+,--bind=}'[fzf: bind]:bindings:'

    {-H,--no-hidden}"[don't search hidden files/directories]"

    {-I,--ignore}"[overrides --no-ignore]"

    {-n,--no-ignore}'[dont respect ignore files]'
    {-l,--no-follow}'[dont follow symlinks]'

    + '(no-regex-pattern)' # non-regex-based search pattern
    {-g,--glob}'[use a glob pattern]'
    {-F,--fixed}'[fixed string search]'

    + filter-misc # filter search
    '*'{-t+,--type=}"[filter search by type]:type:(($zrgf_types))"
    '*'{-e+,--ext=}'[filter search by file extension]:extension:_extensions'
    '*'{-E+,--exclude=}'[exclude files/directories that match the given glob pattern]:glob pattern:_files'
    '*'{-S+,--size=}'[limit search by file size]:size limit:->size'
    '(-o --owner)'{-o+,--owner=}'[filter by owning user and/or group]:owner and/or group:->owner'

    + '(max-results)' # max number of results
    {-R,--max-results}'[limit number of results]:max results:'

    + '(case)' # case-sensitivity
    {-s,--sensitive}'[case sensitive search]'

    + '(no-ignore-full)' # all ignore files
    '(no-ignore-partial)'{-n,--no-ignore}"[don't respect .(git|fd)ignore and global ignore files]"
    $no'(no-ignore-partial)*'{-u,--unrestricted}'[alias for --no-ignore, when repeated also alias for --hidden]'

    + '(regex-pattern)' # regex-based search pattern
    '(no-regex-pattern)'{-G,--regex}'[perform a regex-based search (default)]'

    + '(no-regex-pattern)' # non-regex-based search pattern
    {-g,--glob}'[perform a glob-based search]'
    {-F,--fixed-strings}'[treat pattern as literal string instead of a regex]'

    + dir-depth
    '(--exact-depth -d --max-depth)'{-d+,--max-depth=}'[set max directory depth to descend when searching]:depth'
    '(--exact-depth --min-depth)'{-D,--min-depth=}'[set directory depth to descend before start searching]:depth'

    + prune # pruning
    "(-S --size --exact-depth)"{-p,--prune}"[don't traverse into matching directories]"

    + '(filter-mtime-newer)' # filter by files modified after than
    {-N,--newer=}'[limit search to files/directories modified within the given date/duration]:date or duration'

    + '(filter-mtime-older)' # filter by files modified before than
    {-O,--older=}'[limit search to files/directories modified before the given date/duration]:date or duration'

    + '(follow)' # follow symlinks
    {-L,--follow}'[follow symbolic links to directories]'

    + '(abs-path)' # show absolute paths
    '(long-listing)'{-a,--absolute}'[show absolute paths instead of relative paths]'

    + '(rel-path)' # show absolute paths
    {-A,--relative}'[overrides --absolute]'

    + search-path
    $no'(*)*'{-T,--search-path=}'[set search path (instead of positional <path> arguments)]:directory:_files -/'

    + args # positional arguments
    '1: :_guard "^-*" pattern'
    '(--search-path)*:directory:_files -/'
  )

  _arguments $_arguments_options : $arguments && ret=0

  case ${state} in
    owner)
      compset -P '(\\|)\!'
      if compset -P '*:'; then
        _groups && ret=0
      else
        if
          compset -S ':*' ||
          # Do not add the colon suffix when completing "!user<TAB>
          # (with a starting double-quote) otherwise pressing tab again
          # after the inserted colon "!user:<TAB> will complete history modifiers
          [[ $IPREFIX == (\\|\!)*  && ($QIPREFIX == \"* && -z $QISUFFIX) ]]
        then
          _users && ret=0
        else
          local q
          # Since quotes are needed when using the negation prefix !,
          # automatically remove the colon suffix also when closing the quote
          if [[ $QIPREFIX == [\'\"]* ]]; then
            q=${QIPREFIX:0:1}
          fi
          _users -r ": \t\n\-$q" -S : && ret=0
        fi
      fi
      ;;

    size)
      if compset -P '[-+][0-9]##'; then
        local -a suff=(
          'B:bytes'
          'K:kilobytes  (10^3  = 1000   bytes)'
          'M:megabytes  (10^6  = 1000^2 bytes)'
          'G:gigabytes  (10^9  = 1000^3 bytes)'
          'T:terabytes  (10^12 = 1000^4 bytes)'
          'Ki:kibibytes  ( 2^10 = 1024   bytes)'
          'Mi:mebibytes  ( 2^20 = 1024^2 bytes)'
          'Gi:gigibytes  ( 2^30 = 1024^3 bytes)'
          'Ti:tebibytes  ( 2^40 = 1024^4 bytes)'
        )
        _describe -t units 'size limit units' suff -V 'units'
      elif compset -P '[-+]'; then
        _message -e 'size limit number (full format: <+-><number><unit>)'
      else
        _values 'size limit prefix (full format: <prefix><number><unit>)' \
          '\+[file size must be greater or equal to]'\
          '-[file size must be less than or equal to]' && ret=0
      fi
      ;;
  esac

  return ret
}

_zrgf "$@"
