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

	export let sponsoring_contracts_show = false;
	export let generate_runners = [];
	export let generate_orgs = [];
	export let generate_teams = [];
	//
	export let download_modal_open = false;
	export let download_details = "";

	function generateSponsoringContract(locale) {
		download_modal_open = true;
		if (generate_orgs.length > 0) {
			generateOrgContracts(locale);
		} else if (generate_teams.length > 0) {
			generateTeamContracts(locale);
		} else {
			generateRunnerContracts(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.success($_("pdf-successfully-generated"));
	}

	async function generateTeamContracts(locale) {
		toast.loading($_("generating-pdfs"));
		let totalCount = generate_teams.length;
		let count = 0;
		for (const t of generate_teams) {
			count++;
			download_details = `${t.parentGroup.name} > ${t.name}`;
			const runners = await RunnerTeamService.runnerTeamControllerGetRunners(
				t.id
			);
			await documentServer
				.generateContracts(runners, locale)
				.then((blob) => {
					download(
						blob,
						`${$_("sponsorings")}_${t.name}-${locale}-${createId()}.pdf`
					);
					if (count === totalCount) {
						download_modal_open = false;
					}
				})
				.catch((err) => {});
		}
	}

	async function generateOrgContracts(locale) {
		toast.loading($_("generating-pdf"));
		let totalCount = 0;
		for (const o of generate_orgs) {
			totalCount++;
			for (const t of o.teams) {
				totalCount++;
			}
		}
		console.log({ totalCount });
		let count = 0;
		for (const o of generate_orgs) {
			count++;
			let runners =
				await RunnerOrganizationService.runnerOrganizationControllerGetRunners(
					o.id,
					true
				);
			download_details = o.name;
			await documentServer
				.generateContracts(runners, locale)
				.then((blob) => {
					download(
						blob,
						`${$_("sponsorings")}_${o.name}_direct-${locale}-${createId()}.pdf`
					);
				})
				.catch((err) => {});
			for (const t of o.teams) {
				count++;
				let runners = await RunnerTeamService.runnerTeamControllerGetRunners(
					t.id
				);
				download_details = `${o.name} > ${t.name}`;
				await documentServer
					.generateContracts(runners, locale)
					.then((blob) => {
						download(
							blob,
							`${$_("sponsorings")}_${o.name}_${
								t.name
							}-${locale}-${createId()}.pdf`
						);
						console.log({ count });
						if (count === totalCount) {
							download_modal_open = false;
						}
					})
					.catch((err) => {});
			}
		}
	}

	async function generateRunnerContracts(locale) {
		toast.loading($_("generating-pdf"));
		await documentServer
			.generateContracts(generate_runners, locale)
			.then((blob) => {
				let fileName = `${$_("sponsorings")}-${locale}-${createId()}.pdf`;
				if (generate_runners.length == 1) {
					fileName = `${$_("sponsorings")}_${generate_runners[0].firstname}_${
						generate_runners[0].lastname
					}-${locale}-${createId()}.pdf`;
				}
				download(blob, fileName);
				download_modal_open = false;
			})
			.catch((err) => {
				console.error(err);
			});
	}
</script>

{#if sponsoring_contracts_show}
	<DownloadProgressModal {download_details} modal_open={download_modal_open} />
	<button
		on:click={() => {
			generateSponsoringContract("de");
		}}
		class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm mb-1 lg:mb-0"
	>
		{$_("generate-sponsoring-contracts")}: DE
	</button>
	<button
		on:click={() => {
			generateSponsoringContract("en");
		}}
		class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm mb-1 lg:mb-0"
	>
		{$_("generate-sponsoring-contracts")}: EN
	</button>
{/if}
