# FILE: loadlib.zsh
#
# This file provides a logging facility for stdlib.zsh.  It is always loaded.
typeset -T ZSL_LIB_PATH zsl_lib_path
typeset -UA _zsl_state=()

_zsl_require_one() {
    local name="$1" dir= found=
    if [[ $_zsl_state[$name] = loaded ]]; then
        _zsl_load_dbg "$name already loaded"
        return
    elif [[ $_zsl_state[$name] = loading ]]; then
        _zsl_load_err "$name load in progress, circular require?"
        return 1
    fi

    for dir in "${zsl_lib_path[@]}"; do
        if [[ -r "$dir/$name.zsh" ]]; then
            found="$dir/$name.zsh"
        elif [[ -r "$dir/$name.sh" ]]; then
            found="$dir/$name.sh"
        fi
        if [[ $found ]]; then
            break
        fi
    done

    if [[ $found ]]; then
        _zsl_load_dbg "loading $name from $found"
        _zsl_state[$name]=loading
        . "$found"
        _zsl_mark_loaded "$name"
    fi
}

_zsl_mark_loaded() {
    local mod
    for mod in "$@"; do
        _zsl_state[$mod]=loaded
    done
}

zsl_list_modules() {
    typeset -A seen=() name
    for dir in "${zsl_lib_path[@]}"; do
        _zsl_load_dbg "scanning modules in $dir"
        setopt null_glob
        for file in "$dir"/*.{zsh,sh}; do
            name="$(basename "$file")"
            name="${name%%.(zsh|sh)}"
            if [[ $seen[$name] ]]; then
                continue
            fi
            seen[$name]=$file
            if [[ $_zsl_state[$name] = loaded ]]; then
                print -P -- "%F{cyan}$name%f ($file, %F{green}loaded%f)"
            else
                print -P -- "%F{cyan}$name%f ($file)"
            fi
        done
    done
}

zsl_require() {
    for mod in "$@"; do
        _zsl_require_one "$mod"
    done
}
require() {
    zsl_require "$@"
}

_zsl_load_dbg() {
    if [[ -v functions[_zsl_msg] ]]; then
        _zsl_msg -dbg "$@"
    fi
}

_zsl_load_err() {
    if [[ -v functions[_zsl_msg] ]]; then
        _zsl_msg -error "$@"
    else
        echo "ERR: $*" >&2
    fi
}
