#!/usr/bin/env zsh
# Description:
#   List installed packages (more specifically, view the associative array $zplugs)

local     arg repo tag filter
local     is_loaded=false is_installed=false is_select=false
local -aU repos

tag="${(kj:|:)_zplug_tags[@]}"

while (( $# > 0 ))
do
    arg="$1"
    case "$arg" in
        --select)
            is_select=true
            ;;
        --loaded)
            is_loaded=true
            ;;
        --installed)
            is_installed=true
            ;;
        -*|--*)
            __zplug::core::options::unknown "$arg"
            return $status
            ;;
        "")
            # Invalid
            return 1
            ;;
        */*)
            # Do nothing
            ;;
        *)
            # Do nothing
            ;;
    esac
    shift
done

# If assosiate array "zplugs" is empty,
# it means there are no packages that are managed by zplug
if (( $#zplugs == 0 )); then
    __zplug::io::print::f \
        --die --zplug \
        "no package managed by zplug\n"
    return 1
fi

if $is_loaded; then
    if [[ -s $_zplug_load_log[success] ]]; then
        repos=( ${(u@f)"$(<"$_zplug_load_log[success]")":gs:@:} )
    else
        __zplug::io::print::f \
            --die --zplug \
            "First, you have to run 'zplug load'\n"
        __zplug::log::write::info "$_zplug_load_log[success]: not found or empty\n"
        return 1
    fi
elif $is_installed; then
    # By using a file glob, it's checked whether it really exists
    # A slash is added to the end, but delete it since it's unnecessary
    repos=( "$ZPLUG_REPOS"/*/*(/:gs:"$ZPLUG_REPOS"/:) )
    repos=( "${repos[@]%/}" )
else
    repos=( "${(uk)zplugs[@]:gs:@::}" )
fi

if $is_select; then
    __zplug::utils::shell::search_commands \
        "$ZPLUG_FILTER" \
        | read filter
    if [[ -z $filter ]]; then
        __zplug::io::print::f \
            --die --zplug \
            "There is no available filter in ZPLUG_FILTER\n"
        return 1
    fi
    repos=( ${(@f)"$(print -l "$repos[@]" | ${=filter})"} )
fi

if __zplug::utils::shell::is_atty; then
    # Disply tag information in color
    # when connected to the terminal
    for repo in "$repos[@]"
    do
        builtin printf "$fg[green]$repo$reset_color"
        builtin printf "$fg[blue] => $reset_color"
        builtin printf "${zplugs[$repo]:-"$fg[red]none"}\n"
    done \
        | sed -E 's/('"$tag"'):/'"$fg[yellow]"'\1'"$reset_color"':/g' \
        | sed -E 's/:/:"/g;s/, /", /g;/none$/!s/$/"/g' # quotes tag
    printf "$reset_color"
else
    # When not connected to the termianl,
    # e.g. piped with the grep command (`zplug list | grep zsh`)
    # don't display tag information
    for repo ("$repos[@]") echo "$repo"
fi

# Returns true if a length of repos is greater than zero
return !$#repos
