#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  playlist ACTION
		  playlist -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -h, --help    show this message

		  ACTION        one of:
		                - prompt
		                - run


		Manage the playlist.


		Examples:

		  Enqueue a video:

		    $ playlist prompt


		  Play the next video in the queue:

		    $ playlist run
	EOF
}

for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

while getopts 'h' flag; do
	case "$flag" in
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))
ACTION="${1:-}"

eval "$(assert-arg -- "$ACTION" 'ACTION')"

F="$XDG_DATA_HOME"/euandreh/playlist.txt

prompt() {
	ENTRY="$(zenity --text 'URL of the video to enqueue:' --entry ||:)"
	if [ -n "$ENTRY" ]; then
		printf '%s\n' "$ENTRY" >> "$F"
	fi
}

run() {
	next="$(head -n1 "$F")"
	if [ -z "$next" ]; then
		return
	fi
	mpv "$next"
	printf '%s\n' "$next" >> "queue.$F"
	tail -n+2 "$F" | sponge "$F"
}

case "$ACTION" in
	prompt)
		prompt
		;;
	run)
		run
		;;
	*)
		printf 'Bad ACTION: %s.\n\n' "$ACTION" >&2
		usage >&2
		exit 2
		;;
esac
