#!/usr/bin/env bash

XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache/}"

get_status() {
	s=$1
	if [ "$s" = "Playing" ]; then
		echo "󰏦"
	else
		echo "󰐍"
	fi
}

get_length_time() {
	len=$1
	if [ -n "$len" ]; then
		len=$(bc <<< "$len / 1000000 + 1")
		date -d@"$len" +%M:%S
	else
		echo ""
	fi
}

get_position() {
	pos=$1
	len=$2
	if [[ -n "$pos" && -n $len ]]; then
		bc -l <<< "$pos / $len * 100"
	else
		echo 0
	fi
}

get_position_time() {
	pos=$1
	len=$2
	if [ -n "$pos" ]; then
		date -d@"$(bc <<< "$pos / 1000000")" +%M:%S
	else
		echo ""
	fi
}

get_cover() {
	# COVER_URL=$1
	mkdir -p "$XDG_CACHE_HOME/eww_covers"
	cd "$XDG_CACHE_HOME/eww_covers" || exit

	IMGPATH="$XDG_CACHE_HOME/eww_covers/cover_art.png"

	playerctl -F metadata mpris:artUrl 2>/dev/null | while read -r COVER_URL; do
		if [[ "$COVER_URL" = https* ]]; then
			if [ ! -e "$XDG_CACHE_HOME/eww_covers/$(basename "$COVER_URL")" ]; then
				wget -N "$COVER_URL" -o /dev/null
			fi

			rm "$IMGPATH"
			ln -s "$(basename "$COVER_URL")" "$IMGPATH"

			echo "$IMGPATH"
		elif [ "$COVER_URL" = "" ]; then
			echo ""
		else
			echo "$COVER_URL"
		fi
	done
}

sanitize() {
	echo "$1" | sed 's/"/\"/g'
}

if [ "$1" = "cover" ]; then
	get_cover
else
	playerctl -F metadata -f '{{title}}\{{artist}}\{{status}}\{{position}}\{{mpris:length}}\' 2>/dev/null | while IFS="$(printf '\\')" read -r title artist status position len; do
		jaq --null-input \
			-r -c \
			--arg artist "$(sanitize "$artist")" \
			--arg title "$(sanitize "$title")" \
			--arg status "$(get_status "$status")" \
			--arg pos "$(get_position "$position" "$len")" \
			--arg pos_time "$(get_position_time "$position" "$len")" \
			--arg length "$(get_length_time "$len")" \
			'{"artist": $artist, "title": $title, "status": $status, "position": $pos, "position_time": $pos_time, "length": $length}'
	done
fi
