<script lang="ts">
	import HelpLabel from "#components/labels/HelpLabel.svelte";
	import type { Enums } from "#lib/client/prisma";

	export let max: number = 2;
	export let min: number = 1;
	export let name: string = "";

	// Array of base64 encoded images read into the input.
	import {
		BedarfsausweisWohnenClient,
		BildClient,
		ObjektClient,
		UploadedGebaeudeBild,
		VerbrauchsausweisGewerbeClient,
		VerbrauchsausweisWohnenClient,
	} from "./Ausweis/types.js";
	import { api } from "astro-typesafe-api/client";

	export let images: BildClient[] = [];
	export let ausweis:
		| VerbrauchsausweisWohnenClient
		| VerbrauchsausweisGewerbeClient
		| BedarfsausweisWohnenClient;
	export let objekt: ObjektClient;
	export let kategorie: Enums.BilderKategorie;

	function getAllImages(this: HTMLInputElement) {
		const files = this.files || [];

		if (images.filter((img) => img.kategorie === kategorie).length == max) {
			this.value = "";
			return;
		}

		for (let i = 0; i < files.length; i++) {
			const file = files[i];

			if (file.type !== "image/jpeg" && file.type !== "image/png") {
				continue;
			}

			if (i == max) {
				break;
			}

			const reader = new FileReader();

			reader.onload = () => {
				if (reader.readyState != reader.DONE) {
					return;
				}

				if (!reader.result) {
					return;
				}

				let blob = new Blob([reader.result as ArrayBuffer]);
				let url = URL.createObjectURL(blob);
				let image = new Image();
				image.onload = async () => {
					// Create a new canvas with the desired output size
					const canvas = document.createElement("canvas");
					canvas.width = image.naturalWidth;
					canvas.height = image.naturalHeight;

					// Scale down the image and draw it onto the canvas
					const ctx = canvas.getContext("2d");
					if (!ctx) {
						return;
					}
					ctx.drawImage(
						image,
						0,
						0,
						image.naturalWidth,
						image.naturalHeight
					);

					// Get the scaled-down data from the canvas in the desired output format and quality
					const dataURL = canvas.toDataURL("image/jpeg", 0.8);

					const { uid } = await api.bild.PUT.fetch({
						data: dataURL,
						kategorie
					})

					images.push({ uid, kategorie });
					images = images;

					if (i == Math.min(files.length, max) - 1) {
						this.value = "";
					}
				};

				image.src = url;
			};

			reader.readAsArrayBuffer(file);
		}
	}

	let fileUpload: HTMLInputElement;

	export const upload = () => {
		fileUpload.click();
	};
</script>

<!-- Falls die maximale Anzahl Bilder erreicht wurde grauen wir den input aus und zeigen einen Hilfstext -->
{#if images.filter((image) => image.kategorie === kategorie).length === max}
	<span class="bg-base-200 border px-4 py-2"
		>Maximale Anzahl Bilder wurde erreicht.</span
	>
{:else if max > 1}
	<div class="input-standard">
		<input
			type="file"
			class="file-input file-input-ghost h-[38px]"
			bind:this={fileUpload}
			{name}
			multiple
			on:change={getAllImages}
		/>
		<div class="help-label">
			<HelpLabel>
				<slot />
			</HelpLabel>
		</div>
	</div>
{:else}
	<div class="input-standard">
		<input
			type="file"
			class="file-input file-input-ghost h-[38px]"
			bind:this={fileUpload}
			{name}
			on:change={getAllImages}
		/>
		<div class="help-label">
			<HelpLabel>
				<slot />
			</HelpLabel>
		</div>
	</div>
{/if}
