#!/bin/bash

# got this script from adi1090x, I did not make this

## Get data
STATUS="$(mpc status)"
COVER="/tmp/.music_cover.jpg"
MUSIC_DIR="$HOME/Music"

## Get status
get_status() {
	if [[ $STATUS == *"[playing]"* ]]; then
		echo ""
	else
		echo ""
	fi
}

poll() {
	while [[ 1 == 1 ]]; do
		STATUS="$(mpc status)"
		if [[ -z $STATUS ]]; then
			sleep 30
		fi
		$1
		mpc idle >/dev/null
	done
}

## Get song
get_song() {
	song=$(mpc -f %title% current)
	if [[ -z "$song" ]]; then
		echo "Offline"
	else
		echo "$song"
	fi
}

## Get artist
get_artist() {
	artist=$(mpc -f %artist% current)
	if [[ -z "$artist" ]]; then
		echo "Offline"
	else
		echo "$artist"
	fi
}

## Get time
get_time() {
	time=$(mpc status | grep "%)" | awk '{print $4}' | tr -d '(%)')
	if [[ -z "$time" ]]; then
		echo "0"
	else
		echo "$time"
	fi
}
get_ctime() {
	ctime=$(mpc status | grep "#" | awk '{print $3}' | sed 's|/.*||g')
	if [[ -z "$ctime" ]]; then
		echo "0:00"
	else
		echo "$ctime"
	fi
}
get_ttime() {
	ttime=$(mpc -f %time% current)
	if [[ -z "$ttime" ]]; then
		echo "0:00"
	else
		echo "$ttime"
	fi
}

## Get cover
get_cover() {
	ffmpeg -i "${MUSIC_DIR}/$(mpc current -f %file%)" "${COVER}" -y &>/dev/null
	STATUS=$?

	# Check if the file has a embbeded album art
	if [ "$STATUS" -eq 0 ]; then
		echo "$COVER"
	else
		echo "image/emptympd.png"
	fi
}

get_volume() {
	# gotta get rid of spaces lol
	vol=$(mpc status "%volume%" | awk '{print $1}' | tr -d '%')
	if [[ -z "$vol" ]]; then
		echo "0"
	else
		echo "$vol"
	fi
}

get_random() {
	random=$(mpc status "%random%")
	if [[ -z "$random" ]]; then
		echo "no"
	else
		echo "$random"
	fi
}

get_single() {
	single=$(mpc status "%single%")
	if [[ -z "$single" ]]; then
		echo "no"
	else
		echo "$single"
	fi
}

## Execute accordingly
if [[ "$1" == "--song" ]]; then
	poll get_song
elif [[ "$1" == "--artist" ]]; then
	poll get_artist
elif [[ "$1" == "--status" ]]; then
	poll get_status
elif [[ "$1" == "--time" ]]; then
	get_time
elif [[ "$1" == "--ctime" ]]; then
	get_ctime
elif [[ "$1" == "--ttime" ]]; then
	get_ttime
elif [[ "$1" == "--cover" ]]; then
	poll get_cover
elif [[ "$1" == "--volume" ]]; then
	poll get_volume
elif [[ "$1" == "--single" ]]; then
	poll get_single
elif [[ "$1" == "--random" ]]; then
	poll get_random
elif [[ "$1" == "--toggle" ]]; then
	mpc -q toggle
elif [[ "$1" == "--next" ]]; then
	{
		mpc -q next
		get_cover
	}
elif [[ "$1" == "--prev" ]]; then
	{
		mpc -q prev
		get_cover
	}
fi
