#!/bin/bash

TMP_IMG="/tmp/tidal_art.jpg"
LAST_TRACK_ID=""
title=""
artist=""
track_id=""
arturl=""

playerctl --player=mopidy metadata --follow | while read -r line; do
    case "$line" in
        *xesam:title*)
            title="${line#*xesam:title }"
            ;;
        *xesam:artist*)
            artist="${line#*xesam:artist }"
            ;;
        *xesam:url*)
            uri="${line#*xesam:url }"
            track_id=$(echo "$uri" | awk -F: '{print $NF}')
            ;;
        *mpris:artUrl*)
            arturl="${line#*mpris:artUrl }"
            arturl="${arturl/640x640/1280x1280}"
            ;;
    esac

    if [[ -n "$track_id" && "$track_id" != "$LAST_TRACK_ID" && -n "$title" && -n "$artist" && -n "$arturl" ]]; then
        LAST_TRACK_ID="$track_id"
        echo "[INFO] Nueva pista: $artist - $title (ID $track_id)"
        echo "[INFO] Imagen: $arturl"
        arturl=$(echo "$arturl" | tr -d '\r' | xargs)


        curl -s -L "$arturl" -o "$TMP_IMG"
        notify-send -i "$TMP_IMG" "$title" "$artist"

        # Reset
        title=""
        artist=""
        arturl=""
        uri=""
        track_id=""
    fi
done

