#!/bin/bash
#shellcheck disable=SC1090

. "$(sfpath)" || exit 3

shellfu import pretty


#
# Currency to use when not specified
#
CZKRATES_DEFAULT_CURRENCY=${CZKRATES_DEFAULT_CURRENCY:-USD}


#
# URL to daily table from
#
# The real URL is formed by appending current date.
#
CZKRATES_URL=${CZKRATES_URL:-http://www.cnb.cz/en/financial_markets/foreign_exchange_market/exchange_rate_fixing/daily.txt}

usage() {
    mkusage "[options] [CURRENCY] [MULTIPLIER]" \
            "[options] [MULTIPLIER] [CURRENCY]" \
            "" \
        -o \
            "-D DATE, --date DATE   Use currency rate from DATE instead"    \
            "       of today.  DATEs like 'last sun' work, see section DATE"\
            "       STRING of date(1) for more info."                       \
            "-d, --debug    Turn on debbugging output"                      \
            "-v, --verbose  Be more verbose"
}

type_of() {
    #
    # Print 'num' if $1 is a number (float or integer), 'nil' if empty; 'str' otherwise
    #
    test -z "$1" && echo nil && return
    grep -qxEe '-?[0-9]*[.][0-9]+' <<<"$1" && echo num && return
    grep -qxEe '-?[0-9]+' <<<"$1"          && echo num && return
    echo str
}

parse_rate1() {
    #
    # Parse field $2 from currency $1 data
    #
    local wntcur=$1
    local wntfld=${2:-Rate}
    case "$wntfld" in
        Country|Currency|Amount|Code|Rate) true;;
        *) mkusage "code Country|Currency|Amount|Code|Rate" ;;
    esac
    local date head
    read -r date
    debug "got: date=$date"
    read -r head
    debug "got: head=$head"
    while IFS='|' read -r Country Currency Amount Code Rate;
    do
        debug "got: Country=$Country Currency=$Currency Amount=$Amount Code=$Code Rate=$Rate"
        test "$wntcur" = "$Code" || continue
        case $Amount in
            1) echo "${!wntfld}" ;;
            *) python3 -c "print(float($Rate)/$Amount)" ;;
        esac
    done
}

get_unit_price() {
    #
    # Get price of 1 unit of $currrency
    #
    local table     # table with rate data
    think "getting currrency for: $Curr"
    table=$(curl -f --insecure --silent "$Uri") \
     || die "failed to download rates: $Uri"
    parse_rate1 "$Curr" Rate <<<"$table" | grep .
}

maybe_multiply() {
    #
    # Multiply if needed
    #
    local price
    read -r price
    if test "$Mult" = 1;
    then
        echo "$price"
    else
        think "multiplying by: $Mult"
        python3 -c "print(float($price) * $Mult)"
    fi
}


main() {
    local Uri
    local Curr
    local Mult
    local Date=now
    Uri=$CZKRATES_URL
    #shellcheck disable=SC2034
    while true; do case "$1" in
        -D|--date)    Date=$2;  shift 2 || usage ;;
        -d|--debug)   PRETTY_DEBUG=true;   shift ;;
        -v|--verbose) PRETTY_VERBOSE=true; shift ;;
        -*)           usage ;;
        *)            break ;;
    esac done
    Uri+="?date=$(date -d "$Date" +%d.%m.%Y)"
    case "$(type_of "$1"):$(type_of "$2")" in
        num:num|str:str)    usage ;;
        num:nil|nil:num)    Mult="$1$2"          ;;
        str:nil|nil:str)    Curr="$1$2"          ;;
        str:num)            Curr="$1"; Mult="$2" ;;
        num:str)            Curr="$2"; Mult="$1" ;;
    esac
    Curr="${Curr:-$CZKRATES_DEFAULT_CURRENCY}"
    Curr="${Curr^^}"
    Mult="${Mult:-1}"
    debug -v Uri Curr Mult
    get_unit_price | maybe_multiply
}

debug -v CZKRATES_DEFAULT_CURRENCY

main "$@"