<script>
	import { _ } from "svelte-i18n";
	import {
		DonationService,
		RunnerTeamService,
		RunnerOrganizationService,
	} from "@odit/lfk-client-js";
	import { init } from "@paralleldrive/cuid2";
	import toast from "svelte-french-toast";
	import DocumentServer from "./DocumentServer";
	const createId = init({ length: 10, fingerprint: "lfk-frontend" });
	const documentServer = new DocumentServer(
		config.baseurl_documentserver,
		config.documentserver_key
	);

	export let certificates_show = false;
	export let generate_runners = [];
	export let generate_orgs = [];
	export let generate_teams = [];

	function generateCertificates(locale) {
		if (generate_orgs.length > 0) {
			generateOrgCertificates(locale);
		} else if (generate_teams.length > 0) {
			generateTeamCertificates(locale);
		} else {
			generateRunnerCertificates(locale);
		}
	}
	function download(blob, fileName) {
		const url = window.URL.createObjectURL(blob);
		let a = document.createElement("a");
		a.href = url;
		a.download = fileName;
		document.body.appendChild(a);
		a.click();
		a.remove();
		toast.dismiss();
		toast($_("pdf-successfully-generated"));
	}

	async function generateRunnerCertificates(locale) {
		toast.loading($_("generating-pdf"));
		const current_donations =
			(await DonationService.donationControllerGetAll()) || [];
		let certificateRunners = [];
		for (let runner of generate_runners) {
			runner.distanceDonations =
				current_donations.filter((d) => d.runner?.id == runner.id) || [];
			certificateRunners.push(runner);
		}
		documentServer
			.generateCertificates(certificateRunners, locale)
			.then((blob) => {
				let fileName = `${$_("certificates")}-${locale}.pdf`;
				if (generate_runners.length == 1) {
					fileName = `${$_("certificates")}_${
						generate_runners[0].firstname
					}_${generate_runners[0].lastname}-${locale}-${createId()}.pdf`;
				}
				download(blob, fileName);
			})
			.catch((err) => {});
	}

	async function generateTeamCertificates(locale) {
		toast.loading($_("generating-pdfs"));
		let count = 0;
		const current_donations =
			(await DonationService.donationControllerGetAll()) || [];
		for (const t of generate_teams) {
			const runners = await RunnerTeamService.runnerTeamControllerGetRunners(
				t.id
			);
			let certificateRunners = [];
			for (let runner of runners) {
				runner.distanceDonations =
					current_donations.filter((d) => d.runner?.id == runner.id) || [];
				certificateRunners.push(runner);
			}
			documentServer
				.generateCertificates(certificateRunners, locale)
				.then((blob) => {
					count++;
					download(
						blob,
						`${$_("certificates")}_${t.name}-${locale}-${createId()}.pdf`
					);
				})
				.catch((err) => {});
		}
	}

	async function generateOrgCertificates(locale) {
		toast.loading($_("generating-pdfs"));
		const current_donations =
			(await DonationService.donationControllerGetAll()) || [];
		let count = 0;
		let count_orgs = 0;
		for (const o of generate_orgs) {
			count_orgs++;
			let count = 0;
			let runners =
				await RunnerOrganizationService.runnerOrganizationControllerGetRunners(
					o.id,
					false
				);
			let certificateRunners = [];
			for (let runner of runners) {
				runner.distanceDonations =
					current_donations.filter((d) => d.runner?.id == runner.id) || [];
				certificateRunners.push(runner);
			}
			await documentServer
				.generateCertificates(certificateRunners, locale)
				.then((blob) => {
					download(
						blob,
						`${$_("certificates")}_${o.name}-${locale}-${createId()}.pdf`
					);
				})
				.catch((err) => {});
			for (const t of o.teams) {
				count++;
				let runners = await RunnerTeamService.runnerTeamControllerGetRunners(
					t.id
				);
				let certificateRunners = [];
				for (let runner of runners) {
					runner.distanceDonations =
						current_donations.filter((d) => d.runner?.id == runner.id) || [];
					certificateRunners.push(runner);
				}
				await documentServer
					.generateCertificates(certificateRunners, locale)
					.then((blob) => {
						download(
							blob,
							`${$_("certificates")}_${o.name}_${
								t.name
							}-${locale}-${createId()}.pdf`
						);
						if (
							count === o.teams.length &&
							count_orgs === generate_orgs.length
						) {
							toast.dismiss();
							toast($_("pdfs-successfully-generated"));
						}
					})
					.catch((err) => {});
			}
		}
	}
</script>

{#if certificates_show}
	<div>
		<p class="text-base">{$_("generate-runner-certificates")}</p>
		<div class="inline-flex rounded-lg shadow-2xs">
			<button
				on:click={() => {
					generateCertificates("de");
				}}
				class="py-3 px-4 inline-flex items-center gap-x-2 -ms-px first:rounded-s-lg first:ms-0 last:rounded-e-lg text-sm font-medium focus:z-10 border border-gray-200 bg-blue-600 text-white shadow-2xs hover:bg-blue-800 focus:outline-hidden focus:bg-blue-800 disabled:opacity-50 disabled:pointer-events-none"
			>
				DE
			</button>
			<button
				on:click={() => {
					generateCertificates("en");
				}}
				class="py-3 px-4 inline-flex items-center gap-x-2 -ms-px first:rounded-s-lg first:ms-0 last:rounded-e-lg text-sm font-medium focus:z-10 border border-gray-200 bg-blue-600 text-white shadow-2xs hover:bg-blue-800 focus:outline-hidden focus:bg-blue-800 disabled:opacity-50 disabled:pointer-events-none"
			>
				EN
			</button>
		</div>
	</div>
{/if}
