import * as tfrpc from '/static/tfrpc.js';

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(name, 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>
<button id="import">Import</button>
<button id="export">Export</button>
<button id="delete_all">Delete All</button>
</body>
<script type="module">
	import * as tfrpc from '/static/tfrpc.js';

	document.getElementById('import').addEventListener('click', async function do_import() {
		let input = document.createElement('input');
		input.type = 'file';
		input.style.display = 'none';
		input.addEventListener('change', async function(event) {
			input.parentNode.removeChild(input);
			try {
				let json = JSON.parse(await event.target.files[0].text());
				await tfrpc.rpc.import_data(json);
			} catch (e) {
				alert(e);
			}
		});
		document.body.appendChild(input);
		input.click();
	});

	document.getElementById('export').addEventListener('click', async function do_export() {
		let data = await tfrpc.rpc.export_data();
		if (data) {
			let a = document.createElement('a');
			a.href = 'data:text/json;charset=UTF-8,' + encodeURIComponent(data);
			a.download = '${name}.json';
			a.click();
		}
	});

	document.getElementById('delete_all').addEventListener('click', function do_delete_all() {
		tfrpc.rpc.delete_all_data();
	});
</script>
<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);
}

function load() {
	if (core.user?.credentials?.session) {
		database_list();
	} else {
		app.setDocument(`<!DOCTYPE html>
<html>
<body style="background: #888">
	<h1>Must be signed in to examine databases.</h1>
</body>
</html>`);
	}
}

async function get_database(hash) {
	if (hash.startsWith(':shared:')) {
		let parts = hash.split(':');
		let packageName = parts[3];
		let key = parts.slice(4).join(':');
		return await my_shared_database(packageName, key);
	} else if (hash.length) {
		return await database(hash.split(':').slice(1).join(':'));
	}
}

tfrpc.register(async function export_data() {
	let db = await get_database((await app.getHash())?.substring(1));
	return JSON.stringify(await db.getLike('%'));
});

tfrpc.register(async function import_data(data) {
	let db = await get_database((await app.getHash())?.substring(1));
	for (let [key, value] of Object.entries(data)) {
		await db.set(key, value);
	}
	await main();
});

tfrpc.register(async function delete_all_data() {
	let db = await get_database((await app.getHash())?.substring(1));
	for (let key of await db.getAll()) {
		await db.remove(key);
	}
	await main();
});

async function render(hash) {
	let db = await get_database(hash);
	if (db) {
		key_list(hash, db);
	} else {
		load();
	}
}

core.register('message', async function (message) {
	if (message.event == 'hashChange') {
		render(message.hash.substring(1));
	}
});

async function main() {
	render((await app.getHash())?.substring(1));
}

main();
