async function fetch_info(apps) {
	let result = {};
	for (let [key, value] of Object.entries(apps)) {
		let blob = await ssb.blobGet(value);
		blob = blob ? utf8Decode(blob) : '{}';
		result[key] = JSON.parse(blob);
	}
	return result;
}

async function main() {
	var apps = await fetch_info(await core.apps());
	var core_apps = await fetch_info(await core.apps('core'));
	var doc = `<!DOCTYPE html>
<html>
<head>
	<style>
		.container {
			display: grid;
			grid-template-columns: repeat(auto-fill, 64px);
			justify-content: space-around;
		}
		.app {
			height: 96px;
			width: 64px;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			white-space: nowrap;
		}
		.app > a {
			text-decoration: none;
			max-width: 64px;
			text-overflow: ellipsis ellipsis;
			overflow: hidden;
		}
	</style>
</head>
<body style="background: #888">
<h1 id="apps_title">Apps</h1>
<div id="apps" class="container"></div>
<h1>Core Apps</h1>
<div id="core_apps" class="container"></div>
</body>
<script>
	function populate_apps(id, name, apps) {
		var list = document.getElementById(id);
		for (let app of Object.keys(apps).sort()) {
			let div = list.appendChild(document.createElement('div'));
			div.classList.add('app');

			let icon_a = document.createElement('a');
			let icon = document.createElement('div');
			icon.appendChild(document.createTextNode(apps[app].emoji || '📦'));
			icon.style.fontSize = 'xxx-large';
			icon_a.appendChild(icon);
			icon_a.href = '/~' + name + '/' + app + '/';
			icon_a.target = '_top';
			div.appendChild(icon_a);

			let a = document.createElement('a');
			a.appendChild(document.createTextNode(app));
			a.href = '/~' + name + '/' + app + '/';
			a.target = '_top';
			div.appendChild(a);
		}
	}
	document.getElementById('apps_title').innerText = "~${escape(core.user.credentials?.session?.name || 'guest')}'s Apps";
	populate_apps('apps', '${core.user.credentials?.session?.name}', ${JSON.stringify(apps)});
	populate_apps('core_apps', 'core', ${JSON.stringify(core_apps)});
</script>
</html>`;
	app.setDocument(doc);
}

main();
