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

local show_all,show_new,show_files,show_vid,show_img=1,2,3,4,5

local terra 
render_media_gallery(co: &lib.srv.convo, path: lib.mem.ptr(lib.mem.ref(int8)), uid: uint64, acc: &lib.str.acc)
 -- note that when calling this function, path must be adjusted so that path(0)
 -- eq "media"
	var owner = false
	if co.aid ~= 0 and co.who.id == uid then owner = true end
	var ou = co.srv:actor_fetch_uid(uid)
	if not ou then goto e404 end

	var view = data.view.media_gallery {
		menu = pstr{'',0};
		folders = pstr{'',0};
		directory = pstr{'',0};
		images = pstr{'',0};
	}

	if owner then
		view.menu = P'<a class="pos" href="/media/upload">upload</a><hr>'
	end
	var mode: uint8 = show_new
	var folder: pstr
	if mode == show_new then
		folder = lib.str.plit''
	elseif mode == show_all then
		folder = pstr.null()
	-- else get folder from query str
	end

	var md = co.srv:artifact_enum_uid(uid, folder)
	var gallery: lib.str.acc gallery:init(256)
	var files: lib.str.acc files:init(256) 
	for i=0,md.ct do
		if lib.str.ncmp(md(i)(0).mime, 'image/', 6) == 0 then
			gallery:lpush('<a class="thumb" href="')
			if not owner then
				gallery:lpush('/')
				if ou(0).origin ~= 0 then gallery:lpush('@') end
				gallery:push(ou(0).xid,0):lpush('/')
			end
			gallery:push(md(i)(0).url,0)
				:lpush('"><img src="') :push(md(i)(0).url,0)
				:lpush('/raw"><div class="caption">') :push(md(i)(0).desc,0)
				:lpush('</div></a>')
		else
			files:lpush('<a class="file" href="')
			if not owner then
				gallery:lpush('/')
				if ou(0).origin ~= 0 then gallery:lpush('@') end
				gallery:push(ou(0).xid,0):lpush('/')
			end
			files:push(md(i)(0).url,0)
				:lpush('"><span class="label">'):push(md(i)(0).desc,0)
				:lpush('</span> <span class="mime">'):push(md(i)(0).mime,0)
				:lpush('</span></a>')
		end
		md(i):free()
	end

	view.images = gallery:finalize()
	view.directory = files:finalize()

	if acc ~= nil then
		view:append(acc)
	else
		var pg = view:tostr() defer pg:free()
		co:stdpage([lib.srv.convo.page] {
			title = P'media';
			class = P'media manager';
			cache = false;
			body = pg;
		})
	end

	view.images:free()
	view.directory:free()
	if md:ref() then md:free() end
	do return end

	::e404:: co:complain(404,'media not found','no such media exists on this server')
end

return render_media_gallery
