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

local terra 
render_tweet(co: &lib.srv.convo, p: &lib.store.post, acc: &lib.str.acc)
	var author: &lib.store.actor
	for j = 0, co.actorcache.top do
		if p.author == co.actorcache(j).ptr.id then
			author = co.actorcache(j).ptr
			goto foundauth
		end
	end
	author = co.actorcache:insert(co.srv:actor_fetch_uid(p.author)).ptr

	::foundauth::
	var avistr: lib.str.acc if author.origin == 0 then
		avistr:compose('/avi/',author.handle)
	end
	var timestr: int8[26] lib.osclock.ctime_r(&p.posted, &timestr[0])

	var bhtml = lib.smackdown.html([lib.mem.ptr(int8)] {ptr=p.body,ct=0}) defer bhtml:free()

	var idbuf: int8[lib.math.shorthand.maxlen]
	var idlen = lib.math.shorthand.gen(p.id, idbuf)
	var permalink: lib.str.acc permalink:compose('/post/',{idbuf,idlen})
	var fullname = lib.render.nym(author,0,nil) defer fullname:free()
	var tpl = data.view.tweet {
		text = bhtml;
		subject = cs(lib.coalesce(p.subject,''));
		nym = fullname;
		when = cs(&timestr[0]);
		avatar = cs(author.avatar);
		acctlink = cs(author.xid);
		permalink = permalink:finalize();
		attr = ''
	}

	var attrbuf: int8[32]
	if p.accent ~= -1 and p.accent ~= co.ui_hue then
		var hdecbuf: int8[21]
		var hdec = lib.math.decstr(p.accent, &hdecbuf[20])
		lib.str.cpy(&attrbuf[0], ' style="--hue:')
		lib.str.cpy(&attrbuf[14], hdec)
		var len = &hdecbuf[20] - hdec 
		lib.str.cpy(&attrbuf[14] + len, '"')
		tpl.attr = &attrbuf[0]
	end

	defer tpl.permalink:free()
	if acc ~= nil then tpl:append(acc) return [lib.mem.ptr(int8)]{ptr=nil,ct=0} end
	var txt = tpl:tostr()
	return txt
end
return render_tweet
