#!/usr/bin/env zsh

icons=("󰂎" "󰁺" "󰁻" "󰁼" "󰁽" "󰁾" "󰁿" "󰂀" "󰂁" "󰂂" "󰁹")
num_icons=$(awk -v n="${#icons[@]}" 'BEGIN{print 100 / n}')
BATTERY="/sys/class/power_supply/BAT0"

geticon() {
  level=$(awk -v n="$CAPACITY" -v c="$num_icons" 'BEGIN{print int(n/c-1)}')
  echo "${icons[$level]}"
}

status() {
  if [ "$STATE" = "Charging" ]; then
    echo -n "Charging"

    if [ "$RATE" -gt 0 ]; then
      echo ", $(gettime) left"
    else
      echo ""
    fi
  elif [ "$STATE" = "Discharging" ]; then
    echo "$(gettime)h left"
  else
    echo "Fully Charged"
  fi
}

color() {
  [ "$CAPACITY" -le 20 ] && echo '#f38ba8' || echo '#a6e3a1'
}

wattage() {
  awk -v rate="$RATE" -v uw="1000000" 'BEGIN{print sprintf("%.1f W", rate/uw)}'
}

gettime() {
  FULL=$(cat $BATTERY/energy_full)
  NOW=$(cat $BATTERY/energy_now)

  if [ "$RATE" -gt 0 ]; then
    if [ "$STATE" = "Discharging" ]; then
      EX=$(( ($NOW*1.0) / $RATE))
    else
      EX=$(( (($FULL - $NOW)*1.0) / $RATE))
    fi
    date -u -d@"$(awk -v ex="$EX" 'BEGIN{print ex * 3600}')" +%H:%M
  fi
}

if [ -d "$BATTERY" ]; then
  while true; do
    RATE=$(cat $BATTERY/power_now)
    CAPACITY=$(cat $BATTERY/capacity)
    STATE=$(cat $BATTERY/status)

    echo '{ "visible": true, "icon": "'$(geticon)'", "percentage": '$CAPACITY', "wattage": "'$(wattage)'", "status": "'$(status)'", "color": "'$(color)'" }'
    sleep 15
  done
else
  echo '{ "visible": false,  "icon": "", "percentage": 0, "wattage": "", "status": "", "color": "#a6e3a1" }'
fi
