#!/usr/bin/env bash

set -euo pipefail

script_dir=$(dirname "$(readlink -f "$0")")
sugar_file="$script_dir/data.csv"

latest_sugar=100
condition="normal"

low_trigger=65
low_reset=80
high_trigger=275
high_reset=225
valid_low=0
valid_high=500

ntfy_base=""  # TODO
ntfy_topic="" # TODO
ntfy_auth=""  # TODO

notify_sugar() {
    curl \
        -u "$ntfy_auth" \
        -H "X-Title: $1" \
        -H "X-Tags: $2" \
        -X POST \
        "$ntfy_base/$ntfy_topic" || echo "failed to send sugar notification"
}

invalid_sugar() {
    echo "invalid sugar: got '$latest_sugar'"
}

record_sugar() {
    latest_sugar=$(adb shell cat $(adb shell uiautomator dump | grep -oP '[^ ]+.xml') | \
        xq -x "//*[@resource-id='android:id/shareregv']/*[@resource-id='android:id/id_dex_text']/@text")

    if ! [[ "$latest_sugar" =~ ^[+-]?[0-9]+$ ]]; then
        invalid_sugar
        return
    fi

    if (( $latest_sugar < $valid_low || $latest_sugar > $valid_high )); then
        invalid_sugar
        return
    fi

    timestamp="$(date --iso-8601=seconds)"
    echo "$timestamp,$latest_sugar" >> "$sugar_file"

    if [ "$condition" != "low" ] && (( latest_sugar <= low_trigger )); then
        condition="low"
        echo "[$timestamp] sugar entered $condition condition"
        notify_sugar "LOW SUGAR" "face_with_spiral_eyes"
    elif [ "$condition" == "low" ] && (( latest_sugar >= low_reset )); then
        condition="normal"
        echo "[$timestamp] sugar entered $condition condition"
        notify_sugar "normal sugar" "relaxed"
    elif [ "$condition" == "high" ] && (( latest_sugar <= high_reset )); then
        condition="normal"
        echo "[$timestamp] sugar entered $condition condition"
        notify_sugar "normal sugar" "relaxed"
    elif [ "$condition" != "high" ] && (( latest_sugar >= high_trigger )); then
        condition="high"
        echo "[$timestamp] sugar entered $condition condition"
        notify_sugar "HIGH SUGAR" "exploding_head"
    fi
}

while true; do
    record_sugar
    sleep 60
done
