#!/Users/tblancher/homebrew/bin/bash

PATH=/Users/tblancher/bin:/Users/tblancher/homebrew/opt/coreutils/libexec/gnubin:/usr/bin:/bin
grep=/Users/tblancher/homebrew/opt/grep/libexec/gnubin/grep

declare -A ORGS

#set -x
if [[ "x${1}" == "x" ]]; then
    DATE=$(date +%F).log
else
    DATE=$1
fi

if [[ -f ${DATE} ]]; then
    find_existing_org () {
        for org in ${ORGS[@]}; do
            [[ "${org}" == "${1}" ]] && return 0
        done
        return 1
    }
    get_list_of_orgs () {
        while read; do
            org=$( $grep -Po "\[.*\]" <<< "${REPLY}" | tr -d '[][]' )
            [[ "${org}x" == "x" ]] && continue
#            org="${org##*( )}"  # trim leading whitespace
#            org="${org%%*( )}"  # trim trailing whitespace
#            [[ "${ORGS[@]}" =~ "^${org}$" ]] || ORGS+=("${org}")
#            find_existing_org "${org}" || ORGS+=("${org}")
            ORGS["${org}"]=1
        done
    }

    get_list_of_orgs < ${DATE}

#    IFS=$'\n'; KEYS=($(sort -f <<< "${!ORGS[@]}")); unset IFS 
    KEYS=()
    while IFS= read -rd '' key; do
        KEYS+=( "${key}" )
    done < <(printf '%s\0' "${!ORGS[@]}" | sort -f -z)

#   for (( i=0; i < ${#ORGS[@]}; i++ )); do
    for org in "${KEYS[@]}"; do
        echo "[${org}]"
    done
    
#    for org in "${!ORGS[@]}"; do
#        echo "[${org}]"
#    done

    echo "--"
    echo ${DATE}
    echo
    echo
    echo
    WHOLE=""
    subtotal=0
    for pattern in "${KEYS[@]}"; do
        #echo "pattern=${pattern}" >&2
        $grep -- "\[${pattern}\]" ${DATE} | python timetracker.py
        subtotal=$(bc <<< "scale=2; ${subtotal} + $($grep -- "\[${pattern}\]" ${DATE} | python timetracker.py | $grep "Section" | $grep -Po '\d+\.\d+hrs' | tr -d '[hrs]')")
        printf "Subtotal:  %3.2fhrs\n" ${subtotal}
        echo
        if [[ "${WHOLE}x" == "x" ]]; then
            WHOLE="${pattern}"
        else
            WHOLE="${WHOLE}|${pattern}"
        fi
        echo
    done
    #$grep -Ev "${WHOLE}" ${DATE}.log | timetracker
    echo
    timetracker ${DATE} | $grep "Section" | sed 's/Section/Grand/'

else
    echo "${DATE} does not exist" >&2
fi

#set +x
