# FILE: time.zsh
#
# Time libraries.

zmodload zsh/datetime
zmodload zsh/pcre

parse_iso_date() {
    local ts="$1"
    pcre_compile "(\d+-\d+-\d+T\d+:\d+:\d+[+-]\d+):(\d+)"
    if pcre_match "$ts"; then
        ts="${match[1]}${match[2]}"
    fi
    strftime -r "%FT%T%z" "$ts" || die "invalid time $1"
}

format_rfc822_date() {
    local time="$1"
    local -a args=()
    if [[ $2 ]]; then
        args+=(-s $2)
    fi
    strftime "${args[@]}" "%a, %d %b %Y %H:%M:%S %Z" $time
}

pretty_duration() {
    local seconds= base=
    if [[ $1 = '-base' ]]; then
        base="$2"
        : ${base:=$EPOCHSECONDS}
        seconds=$(($3 - $base))
    else
        seconds="$1"
    fi

    local dir=future
    if (($seconds < 0)); then
        dir=past
        seconds=$((-$seconds))
    fi

    local days=0 hours=0 minutes=0
    if (($seconds > 24 * 3600)); then
        days=$(($seconds / (24 * 3600)))
        seconds=$(($seconds % (24 * 3600)))
    fi
    if (($seconds > 3600)); then
        hours=$(($seconds / 3600))
        seconds=$(($seconds % 3600))
    fi
    if (($seconds > 60)); then
        minutes=$(($seconds / 60))
        seconds=$(($seconds % 60))
    fi

    local s=
    if (($days)); then
        s+="$days days"
    fi
    if (($hours)); then
        if [[ $s ]]; then
            s+=', '
        fi
        s+="$hours hours"
    fi
    if (($minutes)); then
        if [[ $s ]]; then
            s+=', '
        fi
        s+="$minutes minutes"
    fi
    if (($seconds)); then
        if [[ $s =~ '.*,.*' ]]; then
            s+=', and '
        elif [[ $s ]]; then
            s += ' and '
        fi
        s+="$seconds seconds"
    fi
    if [[ $dir = past ]]; then
        s+=" ago"
    fi
    echo -n "$s"
}
