#!/bin/bash

currentArtUrl=""
currentArtPath=""

updateArtPath() {
  local url="$1"

  if [[ "$url" == "$currentArtUrl" ]]; then
    return 0
  fi

  currentArtUrl="$url"
  currentArtPath="/tmp/.eww.media-art.$(tr -dc 'a-zA-Z0-9' </dev/urandom | head -c 10)"

  rm /tmp/.eww.media-art.*

  curl "$url" -o "$currentArtPath" >/dev/null
}

formatReturn() {

  updateArtPath $(playerctl metadata mpris:artUrl)

  playerctl metadata | jq -R -s -c -r --arg artPath "$currentArtPath" 'split("\n") | map(match("(\\w+) {1}([\\w:]+) {3,}(.+)") | {(.captures[1].string): .captures[2].string}) | add | .["mpris:artUrl"] = $artPath'

}

playerctl --follow metadata | while read line; do
  ~/.config/scripts/media.sh display 5
  formatReturn

done
