<script lang="ts">
	import type { BedarfsausweisWohnen, Enums, VerbrauchsausweisGewerbe } from "@ibcornelsen/database/client";

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

	// Array of base64 encoded images read into the input.
	import { GebaeudeClient, UploadedGebaeudeBild, VerbrauchsausweisWohnenClient } from "./Ausweis/types";

	export let images: UploadedGebaeudeBild[] = [];
	export let ausweis: VerbrauchsausweisWohnenClient | VerbrauchsausweisGewerbe | BedarfsausweisWohnen;
	export let gebaeude: GebaeudeClient;
	export let kategorie: Enums.BilderKategorie;

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

		if (images.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")) {
				i--;
				continue;
			}

			if (i == max) {
				break;
			}

			const reader = new FileReader();

			reader.onload = (ev) => {
				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);

					images.push({ base64: dataURL as string, kategorie });
					images = images;
					

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

			reader.readAsArrayBuffer(file);
		}
	}
</script>

{#if max > 1}
	<input type="file" class="file-input file-input-ghost" {name} multiple on:change={getAllImages} />
{:else}
	<input type="file" class="file-input file-input-ghost" {name} on:change={getAllImages} />
{/if}