#!/bin/bash
#Thank you curli
getFollowingChannels() {
	curl -s -H 'Accept: application/vnd.twitchtv.v5+json' \
		-H "Client-ID: $client_id" \
		-H "Authorization: OAuth $oauth" \
		-X GET "https://api.twitch.tv/kraken/streams/followed" |
		jq -c '.streams[] | {"":.channel | {"Streamer ": .name , " playing ": .game}, " for ": .viewers, " viewers ": .video_height}' |
		tr -d '\{\}\:\"\,' |
		awk '{print $0"p"}'
	}

getTwitchUserId() {
	curl -H 'Accept: application/vnd.twitchtv.v5+json' \
		-H "Client-ID: $client_id" \
		-H "Authorization: OAuth $oauth" \
		-X GET "https://api.twitch.tv/kraken/user" |
		jq -c '. | ._id' |
		tr -d '"'
	}

# First argument must be the twitch user id
getFollowingGames() {
	curl -H 'Accept: application/vnd.twitchtv.v5+json' \
		-H "Client-ID: $client_id" \
		-H "Authorization: OAuth $oauth" \
		-X GET "https://api.twitch.tv/kraken/users/${1}/follows/games" |
		jq -c '.follows[] | {"": .game.popularity, " viewers - ": .game.name}' |
		tr -d '\{\}\:\"\,'
	}

# First argument must be the game's name
getChannelsFromGame() {
	curl -s -H 'Accept: application/vnd.twitchtv.v5+json' \
		-H "Client-ID: $client_id" \
		-X GET "https://api.twitch.tv/kraken/streams?game=${1}" |
		jq -c '.streams[] | {"":.channel | {"Streamer ": .name , " playing ": .game}, " for ": .viewers, " viewers ": .video_height}' |
		tr -d '\{\}\:\"\,' |
		awk '{print $0"p"}'
	}

getAllGames() {
	curl -s -H 'Accept: application/vnd.twitchtv.v5+json' \
		-H "Client-ID: $client_id" \
		-H "Authorization: OAuth $oauth" \
		-X GET "https://api.twitch.tv/kraken/games/top?limit=$game_limit" |
		jq -c '.top[] | {"": .viewers, " viewers - ": .game.name}' |
		tr -d '\{\}\:\"\,'
	}
if [[ $1 == "-v" ]]; then
	echo "0.9.0"
	exit 0
fi
cd $(dirname "$0") || exit

source config

quality="best\n1080p60\n1080p\n720p60\n720p\n480p\n360p\naudio_only"
oauth="$(cat oauth | tr -d '\n')"

if [[ -z ${oauth} ]]; then
	echo "ERROR: Missing oauth, use theatron -p if you want to enter private mode"
	notify-send "Theatron" "Copy the token into a file called oauth"
	if [[ ${clip_capabilities} == "true" ]]; then
		scope="clips:edit+user_read"
		auth_url="https://id.twitch.tv/oauth2/authorize?client_id=$client_id&redirect_uri=$redirect_uri&response_type=token&scope=$scope"
		echo "Auth url"
		echo ${auth_url}
		xdg-open "$auth_url"
	fi
	exit 1
fi
	#Private mode
if [[ $1 == "-p" || $1 == "--private" ]]; then
	echo "Entering private mode, check config for list of channels"
	#TODO: Make it possible to enter token into rofi
	channel="$(echo -e ${following} | ${launcher})"
else
	# Check if user wants to see content he's following or not
	if [[ ${default_browse_type} == '' ]]; then
		browse_type_options="Channels you're following\nGames you're following\nAll games\nAll streams\nChange current stream quality or restart previous stream: $(tail -1 .currently_playing)"
		browse_type=$(echo -e "$browse_type_options" | ${launcher})
		echo "Selected $browse_type"
	else
		browse_type=${default_browse_type}
	fi
	# If user wants to browse the channels they follow
	if [[ ${browse_type} == "Games you're following" ]]; then
		# Get the user id, which is needed to get the followed games
		echo "Getting your user ID..."
		user_id=$(getTwitchUserId)
		if [[ -z ${user_id} ]]; then
			notify-send "You need a new token, remove oauth file and restart the app"
			exit 1
		fi
		# Get the games the user is following, note: the amount of viewers does not reflect the live amount (delayed)
		echo "Getting the games you follow..."
		empty_games="You're not following any games, choose me to browse top games instead\nBrowse followed channels"
		games=$(getFollowingGames ${user_id})
		if [[ -z ${games} ]]; then
			games="$empty_games"
		fi
		game=$(echo -e "${games}" | ${launcher})
		if [[ -z ${game} ]]; then
			exit 1
		fi
		echo $game
		if [[ ${game} == "You're not following any games, choose me to browse top channels instead" ]]; then
			browse_type="All games"
			if [[ ${game} == "Browse followed channels" ]]; then
				browse_type="Channels you're following"
			fi
		else
			game_name=$(echo ${game#*viewers - })
			game_formatted=$(echo ${game_name} | jq -s -R -r @uri | rev | cut -c4- | rev)
			# Get the channels from the selected game
			echo "Getting the channels from ${game_name}..."
			channel=$(getChannelsFromGame ${game_formatted} | ${launcher})
			#Check for empty pick
			if [[ -z ${channel} ]]; then
				notify-send "You need to pick a channel..."
				exit 1
			fi
		fi
	fi
	if [[ ${browse_type} == "Channels you're following" ]]; then
		# Get all the channels the user follows
		channel=$(getFollowingChannels | ${launcher})
		if [[ -z $channel ]]; then
			exit 1
		fi
	fi
	# If user wants to browse the games they follow
	# If the user wants to browse every game on Twitch
	# Changed from elif to support going from one browse type to another
	if [[ ${browse_type} == "All games" ]]; then
		# Get all the games (top X by most viewers)
		# TODO: make more requests after the first 100
		echo 'Getting all games...'
		game=$(getAllGames | ${launcher})
		if [[ -z ${game} ]]; then
			notify-send "Selection cancelled"
			exit 1
		fi
		game_name=$(echo ${game#*viewers - })
		game_formatted=$(echo ${game_name} | jq -s -R -r @uri | rev | cut -c4- | rev)
		# Get the channels from the selected game
		echo "Getting the channels from ${game_name}..."
		channel=$(getChannelsFromGame ${game_formatted} | ${launcher})
	fi
	if [[ ${browse_type} == "All streams" ]]; then
		channel=$(getChannelsFromGame | ${launcher})
	fi

	if [[ ${browse_type} == "Change current stream quality"* ]]; then
		pid="$(head -n 1 .currently_playing)"
		channel="$(tail -1 .currently_playing)"
		echo "$channel with quality $picked_quality"
		echo "Killing existing ... $pid"
		kill $pid
		rm .currently_playing
	fi

	not_following=$(echo ${channel} | awk '{print $2}')
	if [[ -n ${not_following} ]]; then
		channel=${not_following}
	fi
	if [[ -z ${channel} ]]; then
		exit 1
	fi
fi
if [[ -z ${channel} ]]; then
	exit 1
	notify-send "Theatron" "Didn't pick anything"
fi
if [[ ${vod_mode} == "true" ]]; then
	#čšć is used to sanitize output easier, so we don't remove every : but only the json key:value colon
	id=$(curl -H 'Accept: application/vnd.twitchtv.v5+json' \
		-H "Client-ID: $client_id" \
		-X GET "https://api.twitch.tv/kraken/users?login=$channel" |
		jq -c '.users[] | ._id' | tr -d '"') \
		live=$(curl -H 'Accept: application/vnd.twitchtv.v5+json' \
		-H "Client-ID: $client_id" \
		-X GET "https://api.twitch.tv/kraken/streams/$id" |
		jq -r '.stream')

	if [[ ${live} != "null"* ]]; then
		live="Channel is live, click me to watch"
	else
		live="Channel is not yet live, use polling service and wait :( "
	fi
	echo "$id" >bId.txt
	#Use ćšć as unique identifiers of what values are and what the keys are
	video=$(curl -H 'Accept: application/vnd.twitchtv.v5+json' \
		-H "Client-ID: $client_id" \
		-X GET "https://api.twitch.tv/kraken/channels/$id/videos?limit=$vod_mode_limit" |
		jq -c --unbuffered '.videos[] | {"čšć" : .title, " (čšć": .created_at, ") čšć": .url}' |
		tr -d '\{\}\"\,' | sed 's/čšć://g' |
		printf "%s\n%s" "$live" "$(cat -)" | ${launcher} | awk 'NF>0{print $NF}')

	# Exit if no selection
	if [[ -z ${video} ]]; then
		exit 1
	fi

fi
picked_quality="best"
if [[ ${always_best} == "false" ]]; then
	picked_quality="$(echo -e ${quality} | ${launcher})"
fi
if [[ ${popup_chat} == "true" || $1 == "-p" ]]; then
	xdg-open https://www.twitch.tv/popout/${channel}/chat?popout=
fi
if [[ -z ${channel} ]]; then
	echo "No channel picked."
	exit 1
else
	streamlink https://www.twitch.tv/${channel} ${picked_quality} --player=mpv ${streamlink_flags} &
	echo -e "$!\n${channel}" >.currently_playing
fi
# vim: ft=sh
