<script>
  import { getLocaleFromNavigator, _ } from "svelte-i18n";
  import {
    RunnerCardService,
    RunnerOrganizationService,
    RunnerTeamService,
  } from "@odit/lfk-client-js";
  import Toastify from "toastify-js";
  import { init } from "@paralleldrive/cuid2";
  const createId = init({ length: 10, fingerprint: "lfk-frontend" });

  export let cards_show = false;
  export let generate_cards = [];
  export let generate_runners = [];
  export let generate_orgs = [];
  export let generate_teams = [];
  $: cards_dropdown_open = false;
  document.addEventListener("click", function (e) {
    if (
      e.target.parentNode?.parentNode?.id != "cards:dropdown" &&
      e.target.parentNode?.parentNode?.id != "cards:dropdown:menu"
    ) {
      cards_dropdown_open = false;
    }
  });

  function generateRunnerCards(locale) {
    cards_dropdown_open = false;

    if (generate_orgs.length > 0) {
      generateOrgCards(locale);
    } else if (generate_teams.length > 0) {
      generateTeamCards(locale);
    } else if (generate_runners.length > 0) {
      generateRunnersCards(locale);
    } else {
      generateCards(locale);
    }
  }

  function generateCards(locale) {
    const toast = Toastify({
      text: $_("generating-pdf"),
      duration: -1,
    }).showToast();
    fetch(
      `${config.baseurl_documentserver}/cards?locale=${locale}&download=true&key=${config.documentserver_key}`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(generate_cards),
      }
    )
      .then((response) => {
        if (response.status != "200") {
          toast.hideToast();
          Toastify({
            text: $_("pdf-generation-failed"),
            duration: 3500,
            backgroundColor:
              "linear-gradient(90deg, hsla(281, 37%, 45%, 1) 0%, hsla(1, 62%, 48%, 1) 100%)",
          }).showToast();
        } else {
          return response.blob();
        }
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        let a = document.createElement("a");
        a.href = url;
        a.download = `${$_("runnercards")}-${locale}-${createId()}.pdf`;
        document.body.appendChild(a);
        a.click();
        a.remove();
        toast.hideToast();
        Toastify({
          text: $_("pdf-successfully-generated"),
          duration: 3500,
          backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
        }).showToast();
      })
      .catch((err) => {
        console.error(err);
      });
  }

  async function generateRunnersCards(locale) {
    const toast = Toastify({
      text: $_("generating-pdf"),
      duration: -1,
    }).showToast();
    const current_cards = await RunnerCardService.runnerCardControllerGetAll();
    let cards = [];
    for (let runner of generate_runners) {
      let card = current_cards.find((c) => c.runner?.id == runner.id);
      if (!card) {
        card = await RunnerCardService.runnerCardControllerPost({
          runner: runner.id,
        });
      }
      cards.push(card);
    }
    fetch(
      `${config.baseurl_documentserver}/cards?locale=${locale}&download=true&key=${config.documentserver_key}`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(cards),
      }
    )
      .then((response) => {
        if (response.status != "200") {
          toast.hideToast();
          Toastify({
            text: $_("pdf-generation-failed"),
            duration: 3500,
            backgroundColor:
              "linear-gradient(90deg, hsla(281, 37%, 45%, 1) 0%, hsla(1, 62%, 48%, 1) 100%)",
          }).showToast();
        } else {
          return response.blob();
        }
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        let a = document.createElement("a");
        a.href = url;
        if (generate_runners.length == 1) {
          a.download = `${$_("runnercards")}_${generate_runners[0].firstname}_${
            generate_runners[0].lastname
          }-${locale}-${createId()}.pdf`;
        } else {
          a.download = `${$_("runnercards")}-${locale}-${createId()}.pdf`;
        }
        document.body.appendChild(a);
        a.click();
        a.remove();
        toast.hideToast();
        Toastify({
          text: $_("pdf-successfully-generated"),
          duration: 3500,
          backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
        }).showToast();
      })
      .catch((err) => {});
  }

  async function generateTeamCards(locale) {
    const toast = Toastify({
      text: $_("generating-pdfs"),
      duration: -1,
    }).showToast();
    let count = 0;
    const current_cards = await RunnerCardService.runnerCardControllerGetAll();
    for (const t of generate_teams) {
      const runners = await RunnerTeamService.runnerTeamControllerGetRunners(
        t.id
      );
      let cards = [];
      for (let runner of runners) {
        let card = current_cards.find((c) => c.runner?.id == runner.id);
        if (!card) {
          card = await RunnerCardService.runnerCardControllerPost({
            runner: runner.id,
          });
        }
        cards.push(card);
      }
      fetch(
        `${config.baseurl_documentserver}/cards?locale=${locale}&download=true&key=${config.documentserver_key}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(cards),
        }
      )
        .then((response) => {
          if (response.status != "200") {
            toast.hideToast();
            Toastify({
              text: $_("pdf-generation-failed"),
              duration: 3500,
              backgroundColor:
                "linear-gradient(90deg, hsla(281, 37%, 45%, 1) 0%, hsla(1, 62%, 48%, 1) 100%)",
            }).showToast();
          } else {
            return response.blob();
          }
        })
        .then((blob) => {
          count++;
          const url = window.URL.createObjectURL(blob);
          let a = document.createElement("a");
          a.href = url;
          a.download = `${$_("runnercards")}_${t.name}-${locale}-${createId()}.pdf`;
          document.body.appendChild(a);
          a.click();
          a.remove();
          if (count === generate_teams.length) {
            toast.hideToast();
            Toastify({
              text: $_("pdfs-successfully-generated"),
              duration: 3500,
              backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
            }).showToast();
          }
        })
        .catch((err) => {});
    }
  }

  async function generateOrgCards(locale) {
    const toast = Toastify({
      text: $_("generating-pdfs"),
      duration: -1,
    }).showToast();
    const current_cards = await RunnerCardService.runnerCardControllerGetAll();
    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 cards = [];
      for (let runner of runners) {
        let card = current_cards.find((c) => c.runner?.id == runner.id);
        if (!card) {
          card = await RunnerCardService.runnerCardControllerPost({
            runner: runner.id,
          });
        }
        cards.push(card);
      }
      await fetch(
        `${config.baseurl_documentserver}/cards?locale=${locale}&download=true&key=${config.documentserver_key}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(cards),
        }
      )
        .then((response) => {
          if (response.status != "200") {
            toast.hideToast();
            Toastify({
              text: $_("pdf-generation-failed"),
              duration: 3500,
              backgroundColor:
                "linear-gradient(90deg, hsla(281, 37%, 45%, 1) 0%, hsla(1, 62%, 48%, 1) 100%)",
            }).showToast();
          } else {
            return response.blob();
          }
        })
        .then((blob) => {
          const url = window.URL.createObjectURL(blob);
          let a = document.createElement("a");
          a.href = url;
          a.download = `${$_("runnercards")}_${o.name}_direct-${locale}-${createId()}.pdf`;
          document.body.appendChild(a);
          a.click();
          a.remove();
          if (count === o.teams.length && count_orgs === generate_orgs.length) {
            toast.hideToast();
            console.log("here");
            Toastify({
              text: $_("pdfs-successfully-generated"),
              duration: 3500,
              backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
            }).showToast();
          }
        })
        .catch((err) => {});
      for (const t of o.teams) {
        count++;
        let runners = await RunnerTeamService.runnerTeamControllerGetRunners(
          t.id
        );
        let cards = [];
        for (let runner of runners) {
          let card = current_cards.find((c) => c.runner?.id == runner.id);
          if (!card) {
            card = await RunnerCardService.runnerCardControllerPost({
              runner: runner.id,
            });
          }
          cards.push(card);
        }
        await fetch(
          `${config.baseurl_documentserver}/cards?locale=${locale}&download=true&key=${config.documentserver_key}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(cards),
          }
        )
          .then((response) => {
            if (response.status != "200") {
              toast.hideToast();
              Toastify({
                text: $_("pdf-generation-failed"),
                duration: 3500,
                backgroundColor:
                  "linear-gradient(90deg, hsla(281, 37%, 45%, 1) 0%, hsla(1, 62%, 48%, 1) 100%)",
              }).showToast();
            } else {
              return response.blob();
            }
          })
          .then((blob) => {
            const url = window.URL.createObjectURL(blob);
            let a = document.createElement("a");
            a.href = url;
            a.download = `${$_("runnercards")}_${o.name}_${
              t.name
            }-${locale}-${createId()}.pdf`;
            document.body.appendChild(a);
            a.click();
            a.remove();
            if (
              count === o.teams.length &&
              count_orgs === generate_orgs.length
            ) {
              toast.hideToast();
              Toastify({
                text: $_("pdfs-successfully-generated"),
                duration: 3500,
                backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
              }).showToast();
            }
          })
          .catch((err) => {});
      }
    }
  }
</script>

{#if cards_show}
  <div id="cards:dropdown" class="relative inline-block">
    <div>
      <button
        on:click={() => {
          cards_dropdown_open = !cards_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-runnercards")}
        <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 cards_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="cards: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={() => {
              generateRunnerCards("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={() => {
              generateRunnerCards("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}
