#!/bin/sh

datadir="/tmp/yt-music"
case $1 in
	songdata)
		if [ -f "$datadir/current" ];then
			out=$(printf '{ "command": ["get_property", "pause"]}\n' | socat - "$datadir/yt-music-mpvsocket" 2>/dev/null)
			printf '{"name":"%s","artist":"%s","cover":"%s","next":"%s","prev":"%s"}' "$(cut -d'>' -f1 < "$datadir/current" | cut -d':' -f2- | sed 's|[^-]*$||g;s|-$||g;s| $||g;s|^ ||g')" "$(cut -d'>' -f1 < "$datadir/current" | sed 's_.* - __;s| $||')" "$datadir/default.jpg" "$(sed -n "/$(cut -d'>' -f2 < "$datadir/current" )/{n;p}" $datadir/next | cut -f1)" "$(sed -n "$(cat $datadir/counter)p" $datadir/next | cut -f1)"
		else
			printf '{"name":"OFFLINE","artist":"offline","cover":"%s/.config/eww/music.png"}' "$HOME"
		fi
		;;
	status)
		out=$(printf '{ "command": ["get_property", "pause"]}\n' | socat - "$datadir/yt-music-mpvsocket" 2>/dev/null)
		if [ -z "$out" ];then
			printf ""
		elif printf "%s" "$out" | grep -q "true";then
			printf "󰐌"
		else
			printf "󰏥"
		fi
		;;
	lyrics)
		if [ -f "$datadir/lyrics" ]; then
			awk -F'\t' -v value="$(echo '{ "command": ["get_property", "time-pos"] }' | socat - "$datadir/yt-music-mpvsocket" | sed -nE 's|.*data":([^,]*).*|\1|p')" '$1 > value*1000 {print $2;exit}' "$datadir/lyrics"
		else
			printf "Lyrics will show here"
		fi
		;;
	time)
		out=$(echo '{"command" :["get_property" , "percent-pos"]}' | socat - "$datadir/yt-music-mpvsocket" 2>/dev/null | sed -nE 's_.*data":([^,]*).*_\1_p')
		printf '%s' "${out:-100}"
		;;
	play_toggle)
		echo cycle pause | socat - "$datadir/yt-music-mpvsocket"
		;;
	next)
		pgrep -f mpvsocket >/dev/null 2>&1 && "$HOME/repos_scripts/yt-music" play_next
		;;
	prev)
		pgrep -f mpvsocket >/dev/null 2>&1 && counter=$(cat "$datadir/counter") && [ "$counter" -gt 0 ] && "$HOME/repos_scripts/yt-music" play "$(sed -n "${counter}p" "$datadir/next")" && printf "%s" "$((counter-1))" > "$datadir/counter" &
		;;
	seek)
		echo "{\"command\" :[\"seek\" ,\"$2\",\"relative-percent\"]}" | socat - "$datadir/yt-music-mpvsocket"
		;;
esac
