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

local terra 
render_notices(
	co: &lib.srv.convo
): {}
	var notes = co.srv:actor_notice_enum(co.who.id)
	
	if notes.ct == 0 then
		co:complain(200,'no news is good news',"you don't have any notices to review")
		return
	end
	defer notes:free()

	var pg = co:stra(512) -- defer pg:free()
	var pflink = co:stra(64)
	var body = co:stra(256)
	var latest: lib.store.timepoint = 0
	for i=0,notes.ct do
		if notes(i).when > latest then latest = notes(i).when end
		var who = co.srv:actor_fetch_uid(notes(i).who) defer who:free()
		if not who then lib.bail('schema integrity violation: nonexistent actor referenced in notification, this is almost certainly an SQL error or bug in the backend implementation') end
		pflink:cue(lib.str.sz(who(0).xid) + 4)
		if who(0).origin == 0 then pflink:lpush('/')
		                      else pflink:lpush('/@') end
		pflink:push(who(0).xid,0)
		var n = data.view.notice {
			avatar = cs(who(0).avatar);
			nym = lib.render.nym(who.ptr,0,nil,true);
			pflink = pstr{ptr = pflink.buf; ct = pflink.sz};
		}
		var notweet = true
		var what = co.srv:post_fetch(notes(i).what) defer what:free()
		switch notes(i).kind do
			case lib.store.noticetype.rt then
				n.kind = P'rt'
				n.act = P'retweeted your post'
			end
			case lib.store.noticetype.like then
				n.kind = P'like'
				n.act = P'likes your post'
			end
			case lib.store.noticetype.reply then
				n.kind = P'reply'
				n.act = P'replied to your post'
				notweet = false
			end
		else goto skip end
		do var idbuf: int8[lib.math.shorthand.maxlen]
			var idlen = lib.math.shorthand.gen(notes(i).what, idbuf)
			var b = lib.smackdown.html(&co.srv.pool, pstr {ptr=what(0).body,ct=0},true) --defer b:free()
			body:lpush(' <a class="quote" href="/post/'):push(&idbuf[0],idlen):lpush('">'):ppush(b):lpush('</a>')
		end
		if not notweet then
			var reply = co.srv:post_fetch(notes(i).reply)
				lib.render.tweet(co,reply.ptr,&body)
			reply:free()
		end
		n.ref = pstr {ptr = body.buf, ct = body.sz}

		n:append(&pg)
		::skip:: n.nym:free()
		         pflink:reset()
				 body:reset()
	end
	--pflink:free()
	pg:lpush('<form method="post"><button name="act" value="clear">clear all notices</button></form>')
	co:livepage([lib.srv.convo.page] {
		title = P'notices', class = P'notices';
		body = pstr {ptr = pg.buf, ct = pg.sz};
		cache = false;
	}, latest)
end

return render_notices
