#!/bin/bash
# mb-music - play Internet streams with mpv or PyRadio
me="${0##*/} ipc"

wmctrl -R cavatransparent
mkdir -p "$HOME/.config/mabox/mb-music/"

CONFFILE="$HOME/.config/mabox/mb-music/mb-music.conf"  # NOT USED YET
# If config file not exist create one with defaults
#if [ ! -f $CONFFILE ]; then
#cat <<EOF > ${CONFFILE}
#
#EOF
#fi

# read config variables from file
#source <(grep = $CONFFILE)

PLAYLIST="$HOME/.config/pyradio/stations.csv"
PLAYLISTYT="$HOME/.config/mabox/mb-music/yt_music_list.csv"
if [ ! -f $PLAYLISTYT ]; then
cat <<EOF > ${PLAYLISTYT}
Legendary Albums,-
R.E.M. - Automatic fot the people 1992,https://www.youtube.com/watch?v=jBUjeOBzkIk
Slayer - South of Heaven 1988,https://www.youtube.com/playlist?list=OLAK5uy_mbXSr6j7jvbIh26_xvtuWqY5Z84BcpxIM
The Cure - Faith 1981,https://www.youtube.com/watch?v=fShNf-NdJx4
Joy Division - Unknown Pleasures 1979,https://www.youtube.com/watch?v=oo7lt0lLOvg
Pink Floyd - The Dark Side Of The Moon 1973,https://www.youtube.com/watch?v=k9ynZnEBtvw
Programming music,-
Meditate like a Witcher (10 hours),https://www.youtube.com/watch?v=-MJi7T4lX80
Tabnine,https://www.youtube.com/watch?v=L_MupB3z1g4
Anonymous Headquarters,https://www.youtube.com/watch?v=Z-VfaG9ZN_U
Connection Lost,https://www.youtube.com/watch?v=l9nh1l8ZIJQ
Infinity,https://www.youtube.com/watch?v=UoPpxj77Vi0
Test Mode,https://www.youtube.com/watch?v=ka4KN2KEGmI
Under the Deep,https://www.youtube.com/watch?v=rr0gvSS1OzE
Brutal,https://www.youtube.com/watch?v=FS8XtrLqIxw
Hidden Service,https://www.youtube.com/watch?v=1-_tyTJHgB8
Easy Thoughts,https://www.youtube.com/watch?v=0V7X9fa0wco
EOF
fi

NOWPLAY="$HOME/.config/mabox/mb-music/.radio-mpv"
NOWPLAYYT="$HOME/.config/mabox/mb-music/.yt-mpv"

menu() {
case $LANG in
    pl*)
		_SNM="<b>Dźwięk i Muzyka</b>"
        _VOL="Sterowanie głośnością"
        _RADIO="Radio Internetowe"
        _PYRADIO="Uruchom <b>PyRadio</b>"
        _LISTEN="Słuchaj radia..."
        _EDITSTATIONS="Edytuj listę stacji radiowych"
        _RADIOBROWSER="Szukaj stacji online"
        _MPV="Odtwarzaj (za pomocą mpv - bez gui)"
        _CAVA="Wizualizacja (cava)"
        _STOP="Wyłącz"
        _PAUSE="Pauza"
        _PLAY="Graj"
        _YTMUSIC="Odtwarzacz MPV"
        _PLAYYT="Odtwarzaj..."
        _EDITMPVPLAYLIST="Edytuj listę MPV"
        _RESETMPVPLAYLIST="Resetuj playlistę MPV"
        _YES_RESET="Resetuj"
        _SETTINGS="Ustawienia"
        ;;
    *)
		_SNM="<b>Music &amp; Sound</b> Menu"
        _VOL="Volume Control"
        _RADIO="Internet Radio"
        _PYRADIO="Launch <b>PyRadio</b>"
        _LISTEN="Listen to the radio..."
        _EDITSTATIONS="Edit radio stations list"
        _RADIOBROWSER="Search Radio Stations online"
        _MPV="Play (with mpv - no gui)"
        _CAVA="Visualiser (cava)"
        _STOP="Quit"
        _PAUSE="Pause"
        _PLAY="Play"
        _YTMUSIC="MPV Player"
        _PLAYYT="Play..."
        _EDITMPVPLAYLIST="Edit MPV playlist"
        _RESETMPVPLAYLIST="Reset MPV playlist"
        _YES_RESET="Reset now"
        _SETTINGS="Settings"
        ;;
esac

#out+=("^sep($_SNM)")
out+=("󰕾   $_VOL	<span bgcolor='#333333' color='#d3d3d3'>  <small> + v</small>  </span>,pavucontrol")
out+=("^sep($_RADIO)")
out+=("$_PYRADIO	<span bgcolor='#333333' color='#d3d3d3'>  <small> + r</small>  </span>,terminator --icon=/usr/share/icons/pyradio.png --geometry=564x440-20-20 -x pyradio -lt")

out+=("^sep()")
NOWPL="0"

#pgrep -f radio-mpv > /dev/null && NOW="$(<"$NOWPLAY")"  NOWPL="1" out0+=("<small>  $STOP <i>$NOW</i></small>,pkill -f radio-mpv;pkill -f yt-mpv")

if pgrep -f radio-mpv > /dev/null 
then
status="$(playerctl -p mpv status)"
NOW="$(<"$NOWPLAY")"  NOWPL="1"
[[ "$status" == "Playing" ]] && out0+=("󰏤  <small>$_PAUSE</small>,playerctl -p mpv pause;${me}") || out0+=("󰐊  <small>$_PLAY</small>,playerctl -p mpv play;${me}")
out0+=("󰓛  <small>$_STOP</small>,pkill -f radio-mpv;${me}")
out0+=("^sep()")
fi

out+=("$_LISTEN,^checkout(mpvradio)")
out2+=("^tag(mpvradio)")

#out2+=("^sep($_LISTEN)")
#mapfile -t stations < "$PLAYLIST"
grp=0
#while IFS=$'\r\n' read -r line
while IFS=, read name url rest
do
#	url=${line#*,}
#	name=${line%,*}
#notify-send.sh "$name" "uerl ${url}"
	name=${name//&/&amp;}
	name=${name/>/}
	name=${name/</}
	url=${url//[[:space:]]/}
	if [[ "${url}" == -* ]];then
	((grp++))
	out2+=("${name},^checkout(grupa${grp})")
	out3+=("^tag(grupa$grp)")
	out3+=("^sep($name)")
	else
		if [ ${grp} != "0" ];then
			out3+=("\"\"\"<small>󰐊  ${name}</small>\"\"\",mb-music play \"${url}\" \"${name}\"")
		else
			out2+=("\"\"\"<small>󰐊  ${name}</small>\"\"\",mb-music play \"${url}\" \"${name}\"")
		fi
	fi
done <<< $(grep -v '^\s*$\|^#\|^\s*#' $PLAYLIST)


out+=("^sep($_YTMUSIC)")
#pgrep -f yt-mpv > /dev/null && NOW="$(<"$NOWPLAYYT")" NOWPL="1" out0+=("<small>  $STOP <i>$NOW</i></small>,pkill -f yt-mpv;pkill -f radio-mpv")
if pgrep -f yt-mpv > /dev/null
then
status="$(playerctl -p mpv status)"
NOW="$(<"$NOWPLAYYT")" NOWPL="1" 
[[ "$status" == "Playing" ]] && out0+=("󰏤  <small>$_PAUSE</small>,playerctl -p mpv pause;${me}") || out0+=("󰐊  <small>$_PLAY</small>,playerctl -p mpv play;${me}")
out0+=("󰓛  <small>$_STOP</small>,pkill -f yt-mpv;${me}")
out0+=("^sep()")
fi

n=$(grep -v '^\s*$\|^#\|^\s*#' ${PLAYLISTYT} |wc -l)

### List yt playlist
if (( $n <= 24 ));then #flat view in rootmenu
	while IFS=$'\r\n' read -r line
	do
		url=${line#*,}
		name=${line%,*}
		name=${name//&/&amp;}
		if [ ${url} == "-" ];then
		out+=("^sep(<small>$name</small>)")
		else
		[[ $name != "" ]] && out+=("\"\"\"<small>󰐊  ${name}</small>\"\"\",mb-music playyt "\""${url}"\"" "\""${name}"\""")
		fi
	done <<< $(grep -v '^\s*$\|^#\|^\s*#' $PLAYLISTYT)
elif (( $n <= 30 ));then # flat view in submenu
	out+=("$_PLAYYT ,^checkout(ytmusic)")
	out2+=("^tag(ytmusic)")
	out2+=("^sep($_YTMUSIC)")
	grp=0
	while IFS=$'\r\n' read -r line
	do
		url=${line#*,}
		name=${line%,*}
		name=${name//&/&amp;}
		if [ ${url} == "-" ];then
		out2+=("^sep(<small>$name</small>)")
		else
		[[ $name != "" ]] && out2+=("\"\"\"<small>󰐊  ${name}</small>\"\"\",mb-music playyt "\""${url}"\"" "\""${name}"\""")
		fi
	done <<< $(grep -v '^\s*$\|^#\|^\s*#' $PLAYLISTYT)
	out2+=("^sep()")
	out2+=("$_EDITPLAYLIST,xdg-open $PLAYLISTYT")
else # n > 30
	out+=("$_PLAYYT ,^checkout(ytmusic)")
	out2+=("^tag(ytmusic)")
	out2+=("^sep($_YTMUSIC)")
	grp=0
	while IFS=$'\r\n' read -r line
	do
		url=${line#*,}
		name=${line%,*}
		name=${name//&/&amp;}
		if [ ${url} == "-" ];then
		((grp++))
		out2+=("${name},^checkout(yt${grp})")
		out3+=("^tag(yt$grp)")
		out3+=("^sep($name)")
		else
			if [ ${grp} != "0" ];then
				out3+=("\"\"\"󰐊  ${name}\"\"\",mb-music playyt "\""${url}"\"" "\""${name}"\""")
			else
				out2+=("\"\"\"󰐊  ${name}\"\"\",mb-music playyt "\""${url}"\"" "\""${name}"\""")
			fi
		fi
	done <<< $(grep -v '^\s*$\|^#\|^\s*#' $PLAYLISTYT)
	
fi

out+=("^sep(VISUALIZER)")
pgrep -f cavatransparent > /dev/null && out+=("$_STOP   󰺢   $_CAVA,mb-music cavakill;mb-music ipc" "Colorize Cava,colorizer-cava -s") || out+=("󰺢   $_CAVA,mb-music cavastart;mb-music ipc")

out+=("^sep()")
out+=("   $_SETTINGS,^checkout(settings)")
out2+=("^tag(settings)")
out2+=("^sep($_RADIO)")
out2+=("   $_EDITSTATIONS,xdg-open $PLAYLIST")
out2+=("   $_RADIOBROWSER,xdg-open https://www.radio-browser.info")
out2+=("^sep($_YTMUSIC)")
out2+=("   $_EDITMPVPLAYLIST,xdg-open $PLAYLISTYT")
out2+=("󰦛   $_RESETMPVPLAYLIST,^checkout(resetmpv)")
out3+=("^tag(resetmpv)")
out3+=("^sep($_RESETMPVPLAYLIST ?)")
out3+=("󰦛   $_YES_RESET,rm ~/.config/mabox/mb-music/yt_music_list.csv;${me}")


### RUN
if [[ "$1" == "-s" || "$1" == "ipc" ]]; then
. /usr/share/mb-jgtools/pipemenu-standalone.cfg
. $HOME/.config/mabox/mabox.conf
if [[ $panels_heightpos == "top" ]]; then
MENU_VALIGN="top"
MENU_MARGIN_Y=${panels_topmargin:-0}
elif [[ $panels_heightpos == "bottom" ]]; then
MENU_VALIGN="bottom"
MENU_MARGIN_Y=${panels_topmargin:-0}
else 
    MENU_VALIGN="center"
    menu_margin_x=4
fi

MENU_PADDING_TOP=$((jgtools_padding+102))
MENU_HALIGN="right"
JGWIDTH=$((300+2*jgtools_padding))

if [[ "$1" == "ipc" ]]; then 
POSITION_MODE="ipc"
else
POSITION_MODE="fixed"
fi
jgmenu_icon_size=0
TABS=200

[ $(pidof picom) ] && MENU_RADIUS=$jgtools_radius
[ -z $jgmenu_use_borders ] && menu_border=0

mkconfigfile

if [[ "$NOWPL" == "1" ]];then
clr="#22FF22"
read -r -d '' NOWPLAYLINES <<EOF
#@rect,,${jgtools_padding},$((jgtools_padding+74)),298,24,0,left,top,,#222222 60,
@rect,,$((jgtools_padding+16)),$((jgtools_padding+70)),$((JGWIDTH-2*jgtools_padding-32)),20,4,left,top,,#222222 75,
@text,,$((jgtools_padding+20)),$((jgtools_padding+70)),$((JGWIDTH-2*jgtools_padding)),20,0,left,top,#FFFFFF 90,,""" 󰐊 󰐊 󰐊 <small>${NOW}</small>"""
EOF
else
clr="#666666"
read -r -d '' NOWPLAYLINES <<EOF
@rect,,$((jgtools_padding+2)),$((jgtools_padding+72)),296,24,0,left,top,,#222222 70,
@text,,$((jgtools_padding+6)),$((jgtools_padding+74)),$((JGWIDTH-2*jgtools_padding)),20,0,left,top,#FFFFFF 90,,""" ${_SNM}  <span bgcolor='#333333' color='#d3d3d3'>  <small> + m</small>  </span>"""
EOF
fi

cat <<EOF > ${MENU_ITEMS}
@rect,,${jgtools_padding},${jgtools_padding},300,100,4,left,top,,#111111 25,

@rect,,$((jgtools_padding+1)),$((jgtools_padding+63)),18,36,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+21)),$((jgtools_padding+43)),18,56,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+41)),$((jgtools_padding+38)),18,61,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+61)),$((jgtools_padding+13)),18,86,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+81)),$((jgtools_padding+43)),18,56,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+101)),$((jgtools_padding+53)),18,46,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+121)),$((jgtools_padding+33)),18,66,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+141)),$((jgtools_padding+53)),18,46,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+161)),$((jgtools_padding+83)),18,16,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+181)),$((jgtools_padding+93)),18,6,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+201)),$((jgtools_padding+97)),18,2,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+221)),$((jgtools_padding+86)),18,13,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+241)),$((jgtools_padding+80)),18,19,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+261)),$((jgtools_padding+58)),18,41,2,left,top,,${clr} 100,
@rect,,$((jgtools_padding+281)),$((jgtools_padding+43)),18,56,2,left,top,,${clr} 100,

${NOWPLAYLINES}

$(printf '%s\n' "${out0[@]}")
$(printf '%s\n' "${out[@]}")
$(printf '%s\n' "${out2[@]}")
$(printf '%s\n' "${out3[@]}")
EOF
jgmenu --config-file=${CONFIG_FILE} --csv-file=${MENU_ITEMS} 2>/dev/null
exit 0
fi

printf '%s\n' "${out0[@]}"
printf '%s\n' "${out[@]}"
printf '%s\n' "${out2[@]}"
printf '%s\n' "${out3[@]}"
}

play() {
    pkill -f radio-mpv
    pkill -f yt-mpv
    notify-send.sh "Playing now: " "$3" --icon=media-tape &
    echo "$3" > "$NOWPLAY"
    mpv --title=radio-mpv "$2" --input-ipc-server=/tmp/mpvsocket
}
playyt() {
    pkill -f yt-mpv
    pkill -f radio-mpv
    notify-send.sh "Playing now: " "$3" --icon=media-tape &
    echo "$3" > "$NOWPLAYYT"
    if [[ "$2" == *"playlist"* ]];then
    mpv --ytdl-raw-options="yes-playlist=" "$2" --no-video --title=yt-mpv --input-ipc-server=/tmp/mpvsocket
    else
    mpv "$2" --no-video --title=yt-mpv --input-ipc-server=/tmp/mpvsocket
    fi
}

# Not really used
stop() {
	stopyt
    pkill -f radio-mpv
    echo "" > "$NOWPLAY"
}
stopyt() {
	stop
    pkill -f yt-mpv
    echo "" > "$NOWPLAYYT"
}
cavastart() {
	cavakill
	transparent-cava ${1} ${2} &2>/dev/null &
}
cavakill() {
	pkill -f cavatransparent &
}
case "$1" in
    play) play "$1" "$2" "$3";;
    playyt) playyt "$1" "$2" "$3";;
    stop) stop;;
    stopyt) stopyt;;
    cavastart) cavastart "$2" "$3";;
    cavakill) cavakill;;
    ipc|*) menu "$1";;
esac
