#!/bin/bash

players="spotify,%any,firefox,chromium,brave,mpd"
player_status=$(playerctl -p $players status)
artist=$(playerctl -p $players metadata --format '{{ artist }}')
title=$(playerctl -p $players metadata --format '{{ title }}')
albumart="$(playerctl -p $players metadata mpris:artUrl | sed -e 's/open.spotify.com/i.scdn.co/g')"
cache="$HOME/.cache/eww/music"

[ ! -d $cache ] && mkdir $cache

status_icon () {
    if [ "$player_status" = "Playing" ]; then
	    echo ""
    elif [ "$player_status" = "Paused" ]; then
	    echo ""
    else
	    echo ""
    fi
}

status_value () {
	player_name=$(playerctl -p $players -l | head -n 1)

	[ "$player_status" = "Playing" ] && echo "Now Playing - via ${player_name^}" || echo "Music"
}

title () {
    [ -z "$title" ] && echo "Nothing Playing" || echo $title
}

artist () {
    if [ "$title" = "Advertisement" ]; then
		echo "Spotify Free"
	else
		if [ -z "$artist" ]; then
			echo "Unknown Artist";
		else
			echo "by $artist"
		fi
	fi
}

cover_notification () {
    cover_dir="$cache/notification-cover"
    [ ! -d $cover_dir ] && mkdir $cover_dir
    cover="$cover_dir/$RANDOM-cover.png"
    fallback="$HOME/.config/bspwm/assets/fallback.png"

    players_pass=$1
    
    if [[ $players_pass == "mpd" ]]; then
      albumart="$(playerctl -p mpd metadata mpris:artUrl)"
    else
      albumart="$(playerctl -p $players_pass metadata mpris:artUrl | sed -e 's/open.spotify.com/i.scdn.co/g')"
    fi

    [ $(playerctl -p $players_pass metadata mpris:artUrl) ] && curl -s "$albumart" --output $cover || cp $fallback $cover

    echo $cover | tail -n 1
}

cover () {
    cover="$cache/cover.png"
    fallback="$HOME/.config/bspwm/assets/fallback.png"

    [ $(playerctl -p $players metadata mpris:artUrl) ] && curl -s "$albumart" --output $cover || cp $fallback $cover 
    echo $cover
}

position () {
    position=$(playerctl -p $players position | sed 's/..\{6\}$//')
	duration=$(playerctl -p $players metadata mpris:length | sed 's/.\{6\}$//')
	
    if [[ $position -gt 0 ]]; then
	    printf "%0d:%02d" $((position%3600/60)) $((position%60))
	    printf " / "
	    printf "%0d:%02d" $((duration%3600/60)) $((duration%60))
    fi
}

case $1 in
    status)
        status_value
    ;;
    status-icon)
        status_icon
    ;;
    title)
        title
    ;;
    artist)
        artist
    ;;
    title-artist)
        echo $(title) - $(artist)
    ;;
    cover)
        cover
    ;;
    cover-notification)
        cover_notification $2
    ;;
    position)
        position || echo "--:-- / --:-- "
    ;;
esac
