#!/bin/sh
# Copyright (C) 2018 devolo AG

timer_prefix_foreach() {
    local prefix="${1}"
    local function="${2}"
    local matched="$(ubus call timer list | jsonfilter -e "@.ids[@~\"^$prefix\"]")"
    local timer_id

    for timer_id in $matched; do
        local name="${timer_id#$prefix}"
        eval "$function \"$timer_id\" \"$name\""
    done
}

timer_foreach() {
    local function="${1}"

    timer_prefix_foreach "" "$function"
}

timer_query() {
    local id="${1}"
    ubus call timer query "{\"id\":\"$id\"}"
}

timer_get_remaining() {
    jsonfilter -s "$(timer_query "${1}")" -e '$.remaining'
}

timer_get_state() {
    jsonfilter -s "$(timer_query "${1}")" -e '$.state'
}

timer_get_initial_timeout() {
    jsonfilter -s "$(timer_query "${1}")" -e '$.timeout'
}
