-- Some Youtube playlist utility functions
-- Cannot be used as is, but may be useful to someone.

wdj.ytapi = {}
local API_KEY = "AIzaSyAfGy9qC7bSvVyw_8dBhK94JNnjrBEaxT8"

function wdj.ytapi.isPlaylistScheme(url)
	return not not url:match("^ytpls://")
end

function wdj.ytapi.urlToPlsVideoId(url)
	return url:match("^ytpls://(.+)@(.+)")
end

function wdj.ytapi.queryPlaylistMeta(plsid, callback)
	local url =
		"https://www.googleapis.com/youtube/v3/playlists?part=snippet&fields=items(snippet(title))&key=" .. API_KEY .. "&id=" .. plsid

	http.Fetch(url, function(body)
		local t = util.JSONToTable(body)

		callback(nil, {
			title = t.items[1].snippet.title
		})
	end)
end
function wdj.ytapi.queryPlaylistVideos(plsid, callback)
	results = {}
	if table.Count(results) >= 200 then
		callback(true, "Abspielen abgebrochen. Die Playlist ist zu groß.")
		return
	end
	local url = "https://www.googleapis.com/youtube/v3/playlistItems?maxResults=50&part=snippet,contentDetails&key="..API_KEY.."&playlistId="..plsid
	http.Fetch(url,
		function(body, len, headers, code)
			if (code == 200) then
				local data = util.JSONToTable(body)
				if data.items then
					for k, v in pairs(data.items) do
						if v.contentDetails.videoPublishedAt then
							table.insert(results, {id = v.contentDetails.videoId})
						end
					end
					callback(nil, results)
				end
			else
				callback(true, "Abspielen abgebrochen. Ein Fehler ist aufgetreten.")
			end
		end,
		function(error)
			callback(true, "Abspielen abgebrochen. Ein Fehler ist aufgetreten.")
		end
	)
end

local plsPatterns = {
	--"https?://www.youtube.com/watch%?v=.*&list=([^&]+)",
	"https?://www.youtube.com/playlist%?list=([^&]+)"
}

function wdj.ytapi.matchPlaylistId(url)
	for _,patt in pairs(plsPatterns) do
		local id = url:match(patt)
		if id then return id end
	end
end
function wdj.ytapi.isPlaylistUrl(url)
	return not not wdj.ytapi.matchPlaylistId(url)
end