const {getUser} = require("../utils/getuser")
const {request} = require("../utils/request")
const cacheManager = require("../eirtubeMods/cache-manager")

async function getVideoComments(id, req, continuation) {
	// Check if video comment data already in cache
	let videoData = cacheManager.read("video")[id]

	if (videoData && videoData.comments && !continuation)
		return videoData.comments
	else {
		const user = getUser(req)
		const settings = user.getSettingsOrDefaults()
		var instanceOrigin = settings.instance
		var outURL = `${instanceOrigin}/api/v1/comments/${id}`

		let commentsFuture = request(outURL)
		let commentData = await commentsFuture
		if (!commentData.ok)
			return commentData.result
		commentData = await commentData.result

		if (commentData.error)
			return commentData

		// Success
		if (videoData) {
			if (!continuation)
				videoData.comments = commentData
			else {
				videoData.comments.comments = videoData.comments.concat(commentData.comments)
				videoData.comments.continuation = commentData.continuation
			}
			cacheManager.write("video", id, videoData)
		}

		return commentData
	}
}

// TODO: ability to use this on community posts?
function getReplies(videoId, commentId, req) {
	let videoData = cacheManager.read("video")[videoId]

	if (videoData && videoData.comments)
		for (const comment of videoData.comments.comments)
			if (comment.commentId == commentId) {
				if (!comment.continuation)
					return []
				break
			}

	// TODO
}

module.exports = {
	getVideoComments,
	getReplies
}
