async function database_list() {
	var dbs = await databases();
	var doc = `<!DOCTYPE html>
<html>
<body style="background: #888">
<h1>Databases</h1>
<ul id="dbs"></ul>
</body>
<script>
	function populate_dbs(id, dbs) {
		var list = document.getElementById(id);
		for (let db of dbs) {
			var li = list.appendChild(document.createElement('li'));
			var a = document.createElement('a');
			a.innerText = db;
			a.href = './#' + db;
			a.target = '_top';
			li.appendChild(a);
		}
	}
	populate_dbs('dbs', ${JSON.stringify(dbs)});
</script>
</html>`;
	app.setDocument(doc);
}

async function key_list(db) {
	let keys = await db.getAll();
	let object = {};
	for (let key of keys) {
		object[key] = await db.get(key);
	}
	let doc = `<!DOCTYPE html>
<html>
<body style="background: #888">
<a href="#" target="_top">back</a>
<h1>Keys</h1>
<ul id="keys"></ul>
</body>
<script>
	function populate_dbs(id, keys) {
		var list = document.getElementById(id);
		for (let [key, value] of Object.entries(keys)) {
			var li = list.appendChild(document.createElement('li'));
			li.innerText = key + ' = ' + value;
		}
	}
	populate_dbs('keys', ${JSON.stringify(object)});
</script>
</html>`;
	app.setDocument(doc);
}

core.register('message', async function (message) {
	if (message.event == 'hashChange') {
		let hash = message.hash.substring(1);
		if (hash.startsWith(':shared:')) {
			let parts = hash.split(':');
			let packageName = parts[3];
			let key = parts.slice(4).join(':');
			key_list(await my_shared_database(packageName, key));
		} else if (hash.length) {
			key_list(await database(hash.split(':').slice(1).join(':')));
		} else {
			database_list();
		}
	}
});

database_list();