<script lang="ts">
	import { Designer } from "@pdfme/ui";
	import { image, text } from "@pdfme/schemas";
	import { variable } from "../../lib/pdf/plugins/variables/index"
	import { onMount } from "svelte";

	import { Template, BLANK_PDF } from "@pdfme/common";

	let template: Template = {
		basePdf: BLANK_PDF,
		schemas: [
			{
			},
		],
	};

	let plugins = { Bild: image, Text: text, Variablen: variable }

	let container: HTMLDivElement;

	let designer: Designer;

	onMount(() => {
		designer = new Designer({ domContainer: container, template, plugins });
	});

	function loadBasePDF() {
		if (!loadTemplateInput.files) return;

		const file = loadTemplateInput.files[0];
		const reader = new FileReader();

		reader.onload = function (e) {
			if (!e.target) return;

			const basePdf = e.target.result as string;
			const newTemplate = { ...template, basePdf };
			designer = new Designer({ domContainer: container, template: newTemplate, plugins });
		};

		reader.readAsDataURL(file);
	}

	function addNewField() {
		template = designer.getTemplate();

		template.schemas[0]["new-field"] = {
				type: "text",
				position: { x: 0, y: 0 },
				width: 10,
				height: 10
		};

		designer.updateTemplate(template);
	}

	function exportTemplate() {
		const template = designer.getTemplate();
		const blob = new Blob([JSON.stringify(template)], { type: "application/json" });
		const url = URL.createObjectURL(blob);
		const a = document.createElement("a");
		a.href = url;
		a.download = "template.json";
		a.click();
	}

	function loadTemplate() {
		const input = document.createElement("input");
		input.type = "file";
		input.accept = ".json";
		input.onchange = function (e) {
			if (!input.files) return;

			const file = input.files[0];
			const reader = new FileReader();

			reader.onload = function (e) {
				if (!e.target) return;

				const template = JSON.parse(e.target.result as string) as Template;
				designer = new Designer({ domContainer: container, template, plugins });
			};

			reader.readAsText(file);
		};

		input.click()
	}

	let loadTemplateInput: HTMLInputElement;
</script>

<header class="mb-4">
	<button class="btn btn-secondary" on:click={() => loadTemplateInput.click()}>Change base PDF</button>
	<button class="btn btn-secondary" on:click={addNewField}>Add new Field</button>
	<button class="btn btn-secondary" on:click={exportTemplate}>Export</button>
	<button class="btn btn-secondary" on:click={loadTemplate}>Load Template</button>
	<a class="btn btn-secondary" href="/dashboard/admin/pdf-viewer">Test in Viewer</a>
	<input type="file" hidden bind:this={loadTemplateInput} on:change={loadBasePDF}>
</header>

<div bind:this={container}></div>
