# shellcheck shell=dash

# use unit suffixes. Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to four or fewer using base 2 for sizes
# TODO: use awk

___x_cmd_hub_u_unit_suffixes_(){
    local base="$1"
    [ -n "$base" ] || M='Provide token' N=hub log:ret:64

    local unit=B
    base=$((base*100))
    while [ "$base" -ge 102400 ] && read -r unit; do
        base=$((base / 1024))
    done <<A
B
KB
MB
GB
TB
PB
A
    x_="$((base / 100)).$((base % 100))" "$unit"
}

___x_cmd_hub_u_unit_suffixes(){
    local base="$1"
    [ -n "$base" ] || M='Provide token' N=hub log:ret:64

    local unit="B"
    base=$((base*100))
    if [ "$base" -ge 102400 ] ; then
        base=$((base/1024))
        unit="KB"
    fi

    if [ "$base" -ge 102400 ] ; then
        base=$((base/1024))
        unit="MB"
    fi

    if [ "$base" -ge 102400 ] ; then
        base=$((base/1024))
        unit="GB"
    fi

    if [ "$base" -ge 102400 ] ; then
        base=$((base/1024))
        unit="TB"
    fi

    if [ "$base" -ge 102400 ] ; then
        base=$((base/1024))
        unit="PB"
    fi

    printf "%s %s" "$((base/100)).$((base%100))" "$unit"
}

___x_cmd_hub_u_percent(){
    local base="$1"
    local total="$2"
    [ -n "$base" ]  || M='Provide base' N=hub log:ret:64
    [ -n "$total" ] || M='Provide total' N=hub log:ret:64

    base="$((base*100*100/total))"
    printf "%s" "$((base/100)).$((base%100)) %"
}

# Parse human-friendly duration into seconds.
# Accepts pure numbers (treated as seconds) or <N><unit> where unit is
# s (seconds), m (minutes), h (hours), d (days), w (weeks).
# Result is returned via the x_ variable.
___x_cmd_hub_u_parse_duration_(){
    local input="$1"
    [ -n "$input" ] || M='Provide duration' N=hub log:ret:64

    case "$input" in
        *[!0-9]*)
            local num="${input%[a-zA-Z]}"
            local unit="${input#"$num"}"
            case "$num" in
                *[!0-9]*)   M="Invalid duration: $input" N=hub log:ret:64 ;;
            esac
            case "$unit" in
                s)          x_="$num"              ;;
                m)          x_=$((num * 60))       ;;
                h)          x_=$((num * 3600))     ;;
                d)          x_=$((num * 86400))    ;;
                w)          x_=$((num * 604800))   ;;
                *)          M="Unknown duration unit '$unit' in: $input" N=hub log:ret:64 ;;
            esac
            ;;
        *)  x_="$input" ;;
    esac
}
