<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 = [];
  $: certificates_dropdown_open = false;
  document.addEventListener("click", function (e) {
    if (
      e.target.parentNode?.parentNode?.id != "certificates:dropdown" &&
      e.target.parentNode?.parentNode?.id != "certificates:dropdown:menu"
    ) {
      certificates_dropdown_open = false;
    }
  });

  function generateCertificates(locale) {
    certificates_dropdown_open = false;

    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,
          true
        );
      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 id="certificates:dropdown" class="relative inline-block">
    <div>
      <button
        on:click={() => {
          certificates_dropdown_open = !certificates_dropdown_open;
        }}
        type="button"
        class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:ml-3 sm:w-auto sm:text-sm inline-flex"
        id="options-menu"
        aria-haspopup="true"
        aria-expanded="true"
      >
        {$_("generate-runner-certificates")}
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          class="-mr-1 ml-2 h-5 w-5"
          ><path fill="none" d="M0 0h24v24H0z" />
          <path
            fill="currentColor"
            d="M3 19h18v2H3v-2zm10-5.83l6.07-6.07 1.42 1.41L12 17 3.52 8.52l1.4-1.42L11 13.17V2h2v11.17z"
          /></svg
        >
      </button>
    </div>
    {#if certificates_dropdown_open}
      <div
        class="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-10"
        id="certificates:dropdown:menu"
      >
        <div
          class="py-1"
          role="menu"
          aria-orientation="vertical"
          aria-labelledby="options-menu"
        >
          <span class="block w-full text-left px-4 py-2 text-sm text-gray-700"
            >{$_("select-language")}</span
          >
          <button
            on:click={() => {
              generateCertificates("de");
            }}
            type="submit"
            class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus:bg-gray-100 focus:text-gray-900"
            role="menuitem"
          >
            {$_("german")}
          </button>
          <button
            on:click={() => {
              generateCertificates("en");
            }}
            type="submit"
            class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus:bg-gray-100 focus:text-gray-900"
            role="menuitem"
          >
            {$_("english")}
          </button>
        </div>
      </div>
    {/if}
  </div>
{/if}
