-- 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_profile(co: &lib.srv.convo, actor: &lib.store.actor)
	var aux: lib.str.acc
	var auxp: pstr
	if co.aid ~= 0 and co.who.id == actor.id then
		auxp = lib.str.plit '<a href="/conf/profile">alter</a>'
	elseif co.aid ~= 0 then
		aux:compose('<a href="/', actor.xid, '/follow">follow</a><a href="/',
			actor.xid, '/chat">chat</a>')
		if co.who.rights.powers:affect_users() then
			aux:lpush('<a href="/'):push(actor.xid,0):lpush('/ctl">control</a>')
		end
		auxp = aux:finalize()
	else
		aux:compose('<a href="/', actor.xid, '/follow">remote follow</a>')
		auxp = aux:finalize()
	end
	var avistr: lib.str.acc if actor.origin == 0 then
		avistr:compose('/avi/',actor.handle)
	end
	var timestr: int8[26] lib.osclock.ctime_r(&actor.knownsince, &timestr[0])

	var strfbuf: int8[28*4]
	var stats = co.srv:actor_stats(actor.id)
		var sn_posts     = cs(lib.math.decstr_friendly(stats.posts, &strfbuf[ [strfbuf.type.N - 1] ]))
		var sn_follows   = cs(lib.math.decstr_friendly(stats.follows, sn_posts.ptr - 1))
		var sn_followers = cs(lib.math.decstr_friendly(stats.followers, sn_follows.ptr - 1))
		var sn_mutuals   = cs(lib.math.decstr_friendly(stats.mutuals, sn_followers.ptr - 1))
	
	var profile = data.view.profile {
		nym = cs(lib.coalesce(actor.nym, actor.handle));
		bio = cs(lib.coalesce(actor.bio, "<em>tall, dark, and mysterious</em>"));
		xid = cs(actor.xid);
		avatar = lib.trn(actor.origin == 0, pstr{ptr=avistr.buf,ct=avistr.sz},
			cs(lib.coalesce(actor.avatar, '/s/default-avatar.webp')));

		nposts = sn_posts, nfollows = sn_follows;
		nfollowers = sn_followers, nmutuals = sn_mutuals;
		tweetday = cs(timestr);
		timephrase = lib.trn(actor.origin == 0, lib.str.plit'joined', lib.str.plit'known since');

		auxbtn = auxp;
	}

	var ret = profile:tostr()
	if actor.origin == 0 then avistr:free() end
	if not (co.aid ~= 0 and co.who.id == actor.id) then auxp:free() end
	return ret
end

return render_profile
