<script lang="ts">
	import UploadImages from "./UploadImages.svelte";
	import type { BedarfsausweisWohnen, Enums, VerbrauchsausweisGewerbe } from "@ibcornelsen/database/client";
	import { GebaeudeClient, UploadedGebaeudeBild, VerbrauchsausweisWohnenClient } from "./Ausweis/types";
	import { RotateCounterClockwise, Trash } from "radix-svelte-icons";

	export let images: UploadedGebaeudeBild[] = [];
	export let max: number = 4;
	export let name: string = "";
	export let ausweis: VerbrauchsausweisWohnenClient | VerbrauchsausweisGewerbe | BedarfsausweisWohnen;
	export let gebaeude: GebaeudeClient;
	export let kategorie: Enums.BilderKategorie

	async function rotateImage(image: UploadedGebaeudeBild): Promise<UploadedGebaeudeBild> {
		return new Promise((resolve, reject) => {
			let img = new Image();
			img.src = image.base64 ? image.base64 : `/bilder/${image.uid}.webp`;
			img.onload = () => {
				let canvas = document.createElement("canvas");
				let ctx = canvas.getContext("2d");
				canvas.width = img.height;
				canvas.height = img.width;
				ctx?.translate(img.height / 2, img.width / 2);
				ctx?.rotate((-90 * Math.PI) / 180);
				ctx?.drawImage(img, -img.width / 2, -img.height / 2);
				image.base64 = canvas.toDataURL("image/webp");
				image.update = true;
				resolve(image)
			};
		})
	}
</script>

<div class="flex flex-col gap-4">
	<UploadImages {name} {kategorie} {max} bind:gebaeude bind:images bind:ausweis />
	<div class="grid grid-cols-2 gap-2">
		{#each images as image, i}
			{#if image.kategorie == kategorie}
				<div class="relative group">
					<img
						src={image.base64 ? image.base64 : `/bilder/${image.uid}.webp`}
						alt={kategorie}
						class="h-full max-h-96 w-full rounded-lg border-2 group-hover:contrast-50 object-cover transition-all"
					/>
					<div class="invisible group-hover:visible absolute left-[50%] top-[50%] translate-x-[-50%] translate-y-[-50%] flex flex-row gap-2">
						<button
						type="button"
						class="rounded-full w-[30px] h-[30px] flex items-center justify-center p-0 bg-[rgba(0,0,0,0.4)]"
						on:click={() => {
							delete images[i];
							images = images.filter((x) => x);
						}}
					>
						<Trash size={20} color="#fff"></Trash>
					</button>
					<button
						type="button"
						class="rounded-full w-[30px] h-[30px] flex items-center justify-center p-0 bg-[rgba(0,0,0,0.4)]"
						on:click={async () => {
							let image = await rotateImage(images[i]);
							images[i] = image;
							images = images
						}}
					>
						<RotateCounterClockwise size={20} color="#fff"></RotateCounterClockwise>
					</button>
					</div>
				</div>
			{/if}
		{/each}
	</div>
</div>