-- vim: ft=terra
local pstr = lib.str.t
local modes = lib.enum [[follow mutual local fedi circle]]
local terra 
requires_login(m: modes.t): bool
	return m == modes.follow
	    or m == modes.mutual
	    or m == modes.circle
end

local terra 
render_timeline(co: &lib.srv.convo, modestr: lib.mem.ref(int8))
	var mode = modes.follow
	var circle: uint64 = 0
	if     modestr:cmp('local') then mode = [modes['local']]
	elseif modestr:cmp('mutual') then mode = modes.mutual
	elseif modestr:cmp('fedi') then mode = modes.fedi
	elseif modestr:cmp('circle') then mode = modes.circle
	end
	if requires_login(mode) and co.aid == 0 then mode = [modes['local']] end


	var stoptime = lib.osclock.time(nil)

	var posts = [lib.mem.vec(lib.mem.ptr(lib.store.post))] { 
		sz = 0, run = 0
	}
	var fetchmode = lib.store.range {
		mode = 1; -- T->I
		from_time = stoptime;
		to_idx = 64;
	}
	if mode == modes.follow or mode == modes.mutual then
		posts = co.srv:timeline_actor_fetch_uid(co.who.id,fetchmode)
	elseif mode == [modes['local']] then
		posts = co.srv:timeline_instance_fetch(fetchmode)
	elseif mode == modes.fedi then
	elseif mode == modes.circle then
	end

	var acc = co:stra(1024)
	var modelabels = arrayof(pstr, 'followed', 'mutuals', 'local instance', 'fediverse', 'circle')
	var modelinks = arrayof(pstr, [modes.members])
	acc:lpush('<div style="text-align: right"><em>showing ')
	for i=0, [modelabels.type.N] do
		if co.aid ~= 0 or not requires_login(i) then
			if i > 0 then acc:lpush(' · ') end
			if i == mode then
				acc:lpush('<strong>'):ppush(modelabels[i]):lpush('</strong>')
			else
				acc:lpush('<a href="/tl/'):ppush(modelinks[i]):lpush('">'):ppush(modelabels[i]):lpush('</a>')
			end
		end
	end
	acc:lpush('</em></div>')
	acc:lpush('<div id="tl" data-live="10">')
	var newest: lib.store.timepoint = 0
	for i = 0, posts.sz do
		if mode == modes.mutual and posts(i).ptr.author ~= co.who.id then
			var author = co:uid2actor(posts(i).ptr.author)
			if not author.relationship.recip.follow() then goto skip end
		end
		lib.render.tweet(co, posts(i).ptr, &acc)
		var t = lib.math.biggest(lib.math.biggest(posts(i).ptr.posted, posts(i).ptr.discovered),posts(i).ptr.edited)
		if t > newest then newest = t end
		::skip:: posts(i):free()
	end
	if posts.run > 0 then posts:free() end
	acc:lpush('</div>')

	var doc = [lib.srv.convo.page] {
		title = 'timeline';
		body = acc:finalize();
		class = 'timeline';
		cache = false;
	}
	co:livepage(doc,newest)
	--doc.body:free()
end
return render_timeline
