<template>
	<q-layout view="lHh Lpr lFf">
		<q-header elevated>
			<q-toolbar>
				<q-toolbar-title>
					Der ESA Much Rechner
				</q-toolbar-title>

				<div>
					<q-btn-group>
						<q-btn
							icon="upload"
							@click="openFileDialog({ multiple: false, accept: '.json' })"
						>
							Import
						</q-btn>
						<q-btn
							icon="download"
							@click="nachDateiExportieren"
						>
							Export
						</q-btn>
					</q-btn-group>

					<span class="q-pl-sm">
						Die Volksfront von Rechnäa
					</span>
				</div>
			</q-toolbar>
		</q-header>

		<q-page-container>
			<slot />
			<!-- <router-view /> -->
		</q-page-container>
	</q-layout>
</template>

<script setup lang="ts">
import { useFileDialog } from '@vueuse/core';
import { saveAs } from 'file-saver';
import { usePersonenStore } from '@/stores/personen-store';
import { useRoute } from 'vue-router';
import { Loading } from 'quasar';

const route = useRoute();

const personenStore = usePersonenStore();
// const { personen } = personenStore;

const nachDateiExportieren = async () => {
	// saveAs(new Blob([JSON.stringify(personenStore.personen)]), 'personen.json', {
	// 	type: 'application/json',
	// });
	// saveAs(new Blob([JSON.stringify(personenStore.personen)]), 'personen.json');
	Loading.show();
	await personenStore.saveRemote(route.params.slug as string);
	Loading.hide();
};

const { open: openFileDialog, reset, onChange } = useFileDialog();

onChange(async files => {
	if (!files) return;

	const file = files[0];

	try {
		personenStore.personen = JSON.parse(await file.text());
		// personenStore.save();

		reset();
	}
	catch (_) {
		// Do nothing
	}
});
</script>