#!/usr/bin/env bash
#
# tubetop2
# Copyright (C) 2018 rehashedsalt <salt@lap-th-e560-0>
#
# Distributed under terms of the MIT license.
#

# Define some functions
function tubetop2-play {
	if [ -z ${1+x} ]; then return 1; fi
	pkill -x xwinwrap
	xwinwrap -ni -fs -b -nf -ov -- mpv -wid WID --title="$name" "$1"
	return 0
}

function tubetop2-download {
	if [ -z ${1+x} ]; then return 1; fi
	videoname="$(youtube-dl -e $1)"
	videoname="${videoname//[^ a-zA-Z0-9:\[\]|()_-]/}"
	video="$cachedir/$videoname.mp4"
	youtube-dl -w "$1" -f 'bestvideo[ext=mp4]+bestaudio[ext=mp4]/best[ext=mp4]' -o "$video"
	errorcode=$?
	if ! [ -r "$video" ]; then
		notify-high "Download Failed" "Video $1 failed to download. youtube-dl gave error code $errorcode." "dialog-error"
		return 2
	fi
	if ! [ "$errorcode" == "0" ]; then
		notify-high "Error" "An error occured while downloading $1. youtube-dl gave error code $errorcode." "dialog-error"
		return $errorcode
	fi
	notify-normal "Download Finished" "\"$videoname\" is now ready to be embedded." "dialog-information"
	return 0
}

function notify-normal {
	if [ -z ${1+x} ] || [ -z ${2+x} ] || [ -z ${3+x} ]; then return 1; fi
	notify-send -u normal -t 3000 -i "$3" -a "$name" "$1" "$2"
}

function notify-high {
	if [ -z ${1+x} ] || [ -z ${2+x} ] || [ -z ${3+x} ]; then return 1; fi
	notify-send -u high -t 10000 -i "$3" -a "$name" "$1" "$2"
}

function log {
	if [ -z ${1+x} ] || [ -z ${2+x} ]; then return 1; fi
	printf "$name: $1: $2\n"
}

name="$(basename $0 .bash)"

# If we were called with --kill, kill all running tubetops
if [ "$1" == "--kill" ]; then
	log 3 "Launched in kill mode. Killing xwinwrap"
	if pkill xwinwrap; then
		notify-normal "Stopped" "Stopped playing all embedded desktop videos" "user-trash"
		log 3 "Successfully killed xwinwrap"
		exit 0
	else
		log 0 "Could not find any instances of xwinwrap"
		exit 1
	fi
fi

# Figure out where to store the videos
if [ -z ${XDG_DATA_HOME+x} ]; then
	cachedir="$HOME/.local/share/$name"
else
	cachedir="$XDG_DATA_HOME/$name"
fi
log 4 "Operating out of \"$cachedir\""

# Make that location if it doesn't exist
if ! [ -d "$cachedir" ]; then
	mkdir -p "$cachedir"
	log 3 "Cache directory didn't exist, so it was made"
fi

# Add a symlink in the user's Videos folder, but only once
if ! [ -f "$cachedir/.symlink" ] && [ -d "$HOME/Videos" ]; then
	log 3 "Added symbolic link to videos in user's Videos folder"
	ln -s "$cachedir" "$HOME/Videos/Tubetop Videos"
	touch "$cachedir/.symlink"
fi

# Get a list of all the videos we have
log 3 "Getting a list of videos"
videos=$(find "$cachedir" -type f -name \*.mp4)
# Build a sanitized list to present to the user
if ! [ "$videos" == "" ]; then
	log 4 "Videos:\n$videos"
	videos_clean=""
	while read video; do
		if ! [ "$videos_clean" == "" ]; then
			videos_clean="$videos_clean"$'\n'
		fi
		video_name="$(basename "$video" .mp4)"
		log 5 "Renaming \"$video\" to \"$video_name\""
		videos_clean="$videos_clean$video_name"
	done <<< "$videos"
	log 4 "Videos, cleaned:\n$videos_clean"
fi

# Make a decision
log 3 "Prompting the user..."
choice="$(rofi -dmenu -p $name <<< "$videos_clean")"

# Validate the input
if [ "$choice" == "" ]; then
	log 0 "User responded with empty string. Terminating."
	exit 0
fi

log 3 "User responded with $choice"

# If the decision is remote, download it. Otherwise, play it
if ! [ -r "$cachedir/$choice.mp4" ]; then
	log 3 "Decided to download $choice"
	notify-normal "Downloading Video" "Video \"$choice\" is being downloaded. It will be available shortly." "drive-harddisk"
	tubetop2-download "$choice"
else
	log 3 "Decided to play \"$choice\" from local files"
	notify-normal "Playing Video" "Embedding \"$choice\" into the desktop." "computer"
	tubetop2-play "$cachedir/$choice.mp4"
fi
log 0 "Quitting"
exit 0