-- vim: ft=terra
local pstr = lib.mem.ptr(int8)
local pref = lib.mem.ref(int8)
local terra cs(s: rawstring)
	return pstr { ptr = s, ct = lib.str.sz(s) }
end

local terra 
render_tweet_replies(
	co: &lib.srv.convo,
	acc: &lib.str.acc,
	id: uint64
): {}
	var replies = co.srv:post_enum_parent(id)
	if replies.ct == 0 then return end
	acc:lpush('<div class="thread">')
	for i=0, replies.ct do
		var post = replies(i).ptr
		lib.render.tweet(co, post, acc)
		render_tweet_replies(co, acc, post.id)
	end
	acc:lpush('</div>')
end

local terra 
render_tweet_page(
	co: &lib.srv.convo,
	path: lib.mem.ptr(pref),
	p: &lib.store.post
): {}
	var livetime = co.srv:thread_latest_arrival_calc(p.id)

	var pg = co:stra(256)
	pg:lpush('<div data-live="10">') -- make the OP refresh too
	lib.render.tweet(co, p, &pg)
	pg:lpush('</div>')

	if co.aid ~= 0 then
		pg:lpush('<form class="action-bar" method="post">')
		if not co.srv:post_liked_uid(co.who.id, p.id)
			then pg:lpush('<button class="pos" name="act" accesskey="l" value="like">like</button>')
			else pg:lpush('<button class="neg" name="act" accesskey="l" value="dislike">dislike</button>')
		end
		pg:lpush('<button class="pos" name="act" accesskey="r" value="rt">retweet</button>')
		if p.author == co.who.id then
			if co.who.rights.powers.edit() then
				pg:lpush('<a class="button" accesskey="e" href="/post/'):rpush(path(1)):lpush('/edit">edit</a>')
			end
			pg:lpush('<a class="neg button" accesskey="d" href="/post/'):rpush(path(1)):lpush('/del">delete</a>')
		elseif co.who.rights.powers.snitch() then
			pg:lpush('<a class="neg button" accesskey="s" href="/post/'):rpush(path(1)):lpush('/report">report</a>')
		end
		-- TODO list user's chosen reaction emoji
		pg:lpush('</form>')

	end
	pg:lpush('<div id="convo" data-live="10">')
	render_tweet_replies(co, &pg, p.id)
	pg:lpush('</div>')

	if co.aid ~= 0 and co.who.rights.powers.post() then
		lib.render.compose(co, nil, &pg)
	end

	var ppg = pg:finalize() --defer ppg:free()
	co:livepage([lib.srv.convo.page] {
		title = 'post'; cache = false;
		class = 'post'; body = ppg;
	}, livetime)

	-- TODO display conversation
	-- perhaps display descendant nodes here, and have a link to the top of the whole tree?
end

return render_tweet_page
