#!/usr/bin/env bash

function get_time_ms {
  date -u +%s%3N
}

icons=("󰛩" "󱩒" "󰛨")

gen_output() {
  icon="${icons[$(awk -v n="$(brillo)" 'BEGIN{print int(n/34)}')]}"
  prcnt=$(brillo | xargs printf "%.*f\n" "0")
  echo '{"percent": '$prcnt', "icon": "'$icon'"}'
}

if [[ $(brillo 2>/dev/stdout 1>/dev/null | head -n1 | awk '{print $1}') == "No" ]]; then
  echo  '{"percent":  100, "icon": "󰛨"}'
elif [ "$1" = "" ]; then
  # initial
  last_time=$(get_time_ms)
  gen_output

  udevadm monitor | rg --line-buffered "backlight" | while read -r _; do
    current_time=$(get_time_ms)
    delta=$((current_time - last_time))
    if [[ $delta -gt 50 ]]; then
      gen_output
      last_time=$(get_time_ms)
    fi
  done
fi