#!/usr/bin/env bash

json() {
    jq -Rn --arg value "$1" '$value'
}

status="$(playerctl status 2>/dev/null || true)"
time_now="$(date +%H:%M)"

if [[ "$status" == "Playing" || "$status" == "Paused" ]]; then
    title="$(playerctl metadata --format '{{ title }}' 2>/dev/null || true)"
    artist="$(playerctl metadata --format '{{ artist }}' 2>/dev/null || true)"
    player="$(playerctl metadata --format '{{ playerName }}' 2>/dev/null || true)"

    [[ -z "$title" ]] && title="Media"

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

    text="$icon  $title"
    [[ -n "$artist" ]] && text="$text  ·  $artist"
    text="$text    $time_now"
    tooltip="${player:-Player} (${status})"
    [[ -n "$artist$title" ]] && tooltip="$tooltip"$'\n'"$artist - $title"
else
    text="  $time_now"
    tooltip="$(date '+%A, %d. %B %Y')"
    class="idle"
fi

printf '{"text":%s,"tooltip":%s,"class":%s}\n' \
    "$(json "$text")" \
    "$(json "$tooltip")" \
    "$(json "$class")"
