#compdef googler
#
# Completion definition for googler.
#
# Author:
#   Zhiming Wang <zmwangx@gmail.com>
#

setopt localoptions noshwordsplit noksharrays

_googler_query_caching_policy () {
    # rebuild if cache is more than a day old
    local -a oldp
    oldp=( $1(Nm+1) )
    (( $#oldp ))
}

_googler_complete_query () {
    local prefix=$words[CURRENT]
    [[ -n $prefix && $prefix != -* ]] || return

    local cache_id=googler_$prefix
    zstyle -s :completion:${curcontext}: cache-policy update_policy
    [[ -z $update_policy ]] && zstyle :completion:${curcontext}: cache_policy _googler_query_caching_policy

    local -a completions
    if _cache_invalid $cache_id || ! _retrieve_cache $cache_id; then
        completions=( ${(f)"$(googler --complete $prefix 2>/dev/null)"} )
        _store_cache $cache_id completions
    fi

    compadd $@ -- $completions
}

local -a args
args=(
    '(- : *)'{-h,--help}'[show help text and exit]'
    '(-s --start)'{-s,--start}'[start at the Nth result]:result number'
    '(-n --count)'{-n,--count}'[show specified number of results (default 10)]:count'
    '(-N --news)'{-N,--news}'[show results from news section]'
    '(-c --tld)'{-c,--tld}'[country-specific search with top-level domain]:top level domain without dot'
    '(-l --lang)'{-l,--lang}'[display in specified language]:language code'
    '(-x --exact)'{-x,--exact}'[disable automatic spelling correction]'
    '(--colorize)--colorize[whether to colorize output]:auto/always/never'
    '(-C --nocolor)'{-C,--nocolor}'[disable color output]'
    '(--colors)--colors[set output colors]:six-letter string'
    '(-j --first --lucky)'{-j,--first,--lucky}'[open the first result in a web browser]'
    '(-t --time)'{-t,--time}'[time limit search]:period (h/d/w/m/y + number)'
    '(-w --site)'{-w,--site}'[search a site using Google]:domain'
    '(--unfilter)--unfilter[do not omit similar results]'
    '(-p --proxy)'{-p,--proxy}'[proxy in HOST:PORT format]:proxy details'
    '(--notweak)--notweak[disable TCP optimizations, forced TLS 1.2]'
    '(--json)--json[output in JSON format; implies --exact and --noprompt]'
    '(--url-handler)--url-handler[cli script or utility]:url opener'
    '(--show-browser-logs)--show-browser-logs[do not suppress browser output]'
    '(--np --noprompt)'{--np,--noprompt}'[perform search and exit, do not prompt for further interactions]'
    '(-u --upgrade)'{-u,--upgrade}'[perform in-place self-upgrade]'
    '(--include-git)--include-git[when used with --upgrade, upgrade to git master]'
    '(- : *)'{-v,--version}'[show version number and exit]'
    '(-d --debug)'{-d,--debug}'[enable debugging]'
    '*:::query:_googler_complete_query'
)
_arguments -S -s $args
