<script lang="ts">
	import { Alert, Button, ButtonGroup, Input } from "@sveltestrap/sveltestrap";
	import type { PageData } from "./$types";
	import apiFetch, { fastFetch, type ApiError } from "$lib/api";
	import saveAs from "file-saver";
	import { addToast } from "$lib/toast";
	import { goto } from "$app/navigation";

	export let data: PageData;

	const exportData = async () => {
		try {
			const config = await apiFetch<any>(
				"GET",
				`/api/guilds/${data.guild.id}/config`,
			);
			downloadBackup(config);
		} catch (e) {
			addToast({
				header: "Error downloading export",
				body: (e as ApiError).message || "Unknown error",
			});
		}
	};

	let importFiles: FileList | undefined;

	const importData = async () => {
		if (!importFiles || importFiles.length === 0) return;
		const fileData = await importFiles[0].text();
		const body = JSON.parse(fileData);

		try {
			await fastFetch("POST", `/api/guilds/${data.guild.id}/config`, body);

			addToast({
				header: "Imported data",
				body: `Successfully imported the settings for ${data.guild.name}!`,
			});

			importFiles = undefined;

			await goto(`/dash/${data.guild.id}`, { invalidateAll: true });
		} catch (e) {
			addToast({
				header: "Error importing data",
				body: (e as ApiError).message || "Unknown error",
			});
		}
	};

	const downloadBackup = (data: any) => {
		const backup = JSON.stringify(data);
		const blob = new Blob([backup], { type: "text/plain;charset=utf-8" });
		saveAs(blob, "server-backup.json");
	};
</script>

<h3>Import and export settings</h3>

<p>
	You can create a backup of your server's configuration here. If you removed
	the bot from your server before, you can import the backup you got then here
	too.
</p>

<Alert color="danger">
	<h4 class="alert-heading">This will overwrite existing settings</h4>
	If you have already made some changes to this server's settings, they will be lost
	when importing a backup.
</Alert>

<p>
	<Input
		type="file"
		id="import"
		bind:files={importFiles}
		accept="text/plain, application/json"
	/>
</p>

<ButtonGroup>
	<Button color="primary" on:click={exportData}>Export settings</Button>
	<Button
		color="secondary"
		on:click={importData}
		disabled={!importFiles || importFiles.length === 0}>Import settings</Button
	>
</ButtonGroup>
