#!/bin/sh
. /lib/functions.sh
. /lib/functions/timer.sh
. /usr/share/libubox/jshn.sh
. /lib/delos-functions.sh

handle_quota_entry() {
    local name="$1"
    local mac="$2"
    local day="$3"

    [ ! "$(config_get "$name" station)" = "$mac" ] && return
    config_get ENTRY_DAY "$name" "daysofweek" "Monday Tuesday Wednesday Thursday Friday Saturday Sunday"
    case "$ENTRY_DAY" in
        *$day*)
            config_get "$name" quota
            ;;
    esac
}

find_station_quota() {
    local mac="$1"
    local day="$(date +%A)"

    echo "$(config_foreach handle_quota_entry entry "$mac" "$day")"
}

add_station_quota_info() {
    local timer_id="$1"
    # technically the timer_id without prefix; we always put the mac there
    local mac="$2"
    local status

    # if we don't have a configured quota for this station, ignore it
    local quota="$(find_station_quota "$mac")"
    [ -z "$quota" ] && return
    quota="$(dvl_time_to_mseconds "$quota")"

    json_add_object "$mac"
    state="$(timer_get_state $timer_id)"
    json_add_string state "$state"
    if [ ! "$state" = "EXPIRED" ]; then
        json_add_string remaining "$(timer_get_remaining $timer_id)"
    fi
    json_add_string quota "$quota"
    json_close_object
}

case "$1" in
        list)
            echo '{"status":{}}'
        ;;

        call)
            case "$2" in
                status)
                    config_load "station_quota"
                    config_get_bool QUOTA_ENABLED global enabled 0
                    # if the station quota isn't enabled, ignore timers
                    if [ "$QUOTA_ENABLED" -eq 0 ]; then
                        echo "{}"
                        exit 0
                    fi

                    json_init
                    timer_prefix_foreach "quota-" add_station_quota_info
                    json_dump
                ;;
            esac
        ;;
esac