<script>
  import { _ } from "svelte-i18n";
  import {
    RunnerService,
    RunnerTeamService,
    RunnerOrganizationService,
  } from "@odit/lfk-client-js";
  import ThFilterGroup from "./ThFilterGroup.svelte";
  import { DataHandler, Datatable, Th, ThFilter } from "@vincjo/datatables";
  import store from "../../store";
  import GenerateSponsoringContracts from "../pdf_generation/GenerateSponsoringContracts.svelte";
  import GenerateRunnerCards from "../pdf_generation/GenerateRunnerCards.svelte";
  import GenerateRunnerCertificates from "../pdf_generation/GenerateRunnerCertificates.svelte";
  import { onMount } from "svelte";
  $: active_deletes = [];
  let dataLoaded = false;
  let current_runners = [];
  const handler = new DataHandler(current_runners, { rowsPerPage: 50 });
  const rows = handler.getRows();
  $: sponsoring_contracts_show = generate_runners.length > 0;
  $: cards_show = generate_runners.length > 0;
  $: certificates_show = generate_runners.length > 0;
  $: generate_runners = []; //current_runners.filter((r) => r.selected === true);
  $: teams = [];
  $: orgs = [];
  $: mappedteams = teams.map(function (g) {
    return { value: g.id, label: g.parentGroup.name + " > " + g.name };
  });
  $: selectgroups = orgs
    .map(function (g) {
      return { value: g.id, label: g.name };
    })
    .concat(mappedteams);
  onMount(() => {
    RunnerService.runnerControllerGetAll().then((val) => {
      current_runners = val;
      dataLoaded = true;
      handler.setRows(val);
    });
    RunnerTeamService.runnerTeamControllerGetAll().then((val) => {
      teams = val;
    });
    RunnerOrganizationService.runnerOrganizationControllerGetAll().then(
      (val) => {
        orgs = val;
      }
    );
  });
</script>

{#if store.state.jwtinfo.userdetails.permissions.includes("RUNNER:GET")}
  {#if !dataLoaded}
    <div
      class="bg-teal-lightest border-t-4 border-teal rounded-b text-teal-darkest px-4 py-3 shadow-md my-2"
      role="alert"
    >
      <p class="font-bold">{$_("runners-are-being-loaded")}</p>
      <p class="text-sm">{$_("this-might-take-a-moment")}</p>
    </div>
  {:else}
    <div class="h-12">
      <GenerateSponsoringContracts
        bind:sponsoring_contracts_show
        bind:generate_runners
      />
      <GenerateRunnerCards bind:cards_show bind:generate_runners />
      <GenerateRunnerCertificates
        bind:certificates_show
        bind:generate_runners
      />
    </div>
    <Datatable {handler}>
      <table>
        <thead>
          <tr>
            <th style="border-bottom: 1px solid #ddd;">
              <input
                type="checkbox"
                class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
                checked={generate_runners.length == current_runners.length}
                on:click={() => {
                  if (generate_runners.length != current_runners.length) {
                    generate_runners = current_runners;
                  } else {
                    generate_runners = [];
                  }
                }}
              />
            </th>
            <Th {handler} orderBy="id">ID</Th>
            <Th {handler} orderBy="firstname">First Name</Th>
            <Th {handler} orderBy="middlename">Middle Name</Th>
            <Th {handler} orderBy="lastname">Last Name</Th>
            <th style="border-bottom: 1px solid #ddd;">Gruppe</th>
            <Th {handler} orderBy="distance">Distanz</Th>
            <th style="border-bottom: 1px solid #ddd;">{$_("action")}</th>
          </tr>
          <tr>
            <th style="border-bottom: 1px solid #ddd;" />
            <ThFilter {handler} filterBy="id" />
            <ThFilter {handler} filterBy="firstname" />
            <ThFilter {handler} filterBy="middlename" />
            <ThFilter {handler} filterBy="lastname" />
            <ThFilterGroup groups={selectgroups} {handler} />
            <th style="border-bottom: 1px solid #ddd;" />
            <th style="border-bottom: 1px solid #ddd;" />
          </tr>
        </thead>
        <tbody>
          {#each $rows as row}
            <tr>
              <td>
                <input
                  type="checkbox"
                  class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
                  checked={generate_runners.filter((i)=>i.id == row.id).length > 0}
                  on:click={() => {
                    if (
                      generate_runners.findIndex((i) => i.id == row.id) == -1
                    ) {
                      generate_runners.push(row);
                      generate_runners = generate_runners;
                    } else {
                      generate_runners = generate_runners.filter(
                        (r) => r.id != row.id
                      );
                    }
                    console.log(generate_runners)
                  }}
                />
              </td>
              <td>{row.id}</td>
              <td>{row.firstname}</td>
              <td>{row.middlename || ""}</td>
              <td>{row.lastname}</td>
              <td
                >{#if row.group.responseType === "RUNNERTEAM"}
                  <a
                    href="../teams/{row.group.id}"
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800"
                    >{row.group.parentGroup.name} &gt; {row.group.name}</a
                  >
                {/if}
                {#if row.group.responseType === "RUNNERORGANIZATION"}
                  <a
                    href="../orgs/{row.group.id}"
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800"
                    >{row.group.name}</a
                  >
                {/if}</td
              >
              <td>{row.distance / 1000} km</td>
              <td>
                {#if active_deletes[row.id] === true}
                  <button
                    on:click={() => {
                      active_deletes[row.id] = false;
                    }}
                    tabindex="0"
                    class="ml-4 text-indigo-600 hover:text-indigo-900 cursor-pointer"
                    >{$_("cancel-delete")}</button
                  >
                  <button
                    on:click={() => {
                      RunnerService.runnerControllerRemove(row.id, true)
                        .then((resp) => {
                          current_runners = current_runners.filter(
                            (obj) => obj.id !== row.id
                          );
                        })
                        .catch((err) => {});
                    }}
                    tabindex="0"
                    class="ml-4 text-red-600 hover:text-red-900 cursor-pointer"
                    >{$_("confirm-delete")}</button
                  >
                {:else}
                  <a
                    href="./{row.id}"
                    class="text-indigo-600 hover:text-indigo-900"
                    >{$_("details")}</a
                  >
                  {#if store.state.jwtinfo.userdetails.permissions.includes("RUNNER:DELETE")}
                    <button
                      on:click={() => {
                        active_deletes[row.id] = true;
                      }}
                      tabindex="0"
                      class="ml-4 text-red-600 hover:text-red-900 cursor-pointer"
                      >{$_("delete")}</button
                    >
                  {/if}
                {/if}
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    </Datatable>
  {/if}
{/if}

<style>
  thead {
    background: #fff;
  }
  thead {
    position: sticky;
    inset-block-start: 0;
  }
  tbody td {
    padding: 4px;
  }
  tbody tr:nth-child(even) {
    background: #fafafa;
  }
  tbody tr {
    transition: all, 0.2s;
  }
  tbody tr:hover {
    background: #f5f5f5;
  }
</style>
