#!/usr/bin/env bash
# Emit current player state as JSON for eww (playerctl). Caches remote cover art.
cache="$HOME/.cache/eww"
mkdir -p "$cache"

last=""
last_art=""

emit() {
  local status title artist art icon cover
  status=$(playerctl status 2>/dev/null)
  [ -z "$status" ] && status="Stopped"
  title=$(playerctl metadata title 2>/dev/null)
  artist=$(playerctl metadata artist 2>/dev/null)
  art=$(playerctl metadata mpris:artUrl 2>/dev/null)

  if [ "$status" = "Playing" ]; then icon="󰏤"; else icon="󰐊"; fi

  cover=""
  case "$art" in
    file://*) cover="${art#file://}";;
    http*://*)
      if [ "$art" != "$last_art" ]; then
        curl -sL --max-time 5 "$art" -o "$cache/cover.img" 2>/dev/null && cover="$cache/cover.img"
      else
        cover="$cache/cover.img"
      fi
      ;;
  esac
  last_art="$art"

  jq -nc --arg s "$status" --arg t "$title" --arg a "$artist" --arg i "$icon" --arg c "$cover" \
    '{status:$s,title:$t,artist:$a,icon:$i,cover:$c}'
}

while true; do
  cur=$(emit)
  if [ "$cur" != "$last" ]; then
    printf '%s\n' "$cur"
    last="$cur"
  fi
  sleep 1
done
