<script>
  import { _ } from "svelte-i18n";
  import {
    RunnerService,
    RunnerTeamService,
    RunnerOrganizationService,
  } from "@odit/lfk-client-js";
  import store from "../../store";
  import RunnersEmptyState from "./RunnersEmptyState.svelte";
  import Select from "svelte-select";
  import GenerateSponsoringContracts from "../pdf_generation/GenerateSponsoringContracts.svelte";
  import GenerateRunnerCards from "../pdf_generation/GenerateRunnerCards.svelte";
  import GenerateRunnerCertificates from "../pdf_generation/GenerateRunnerCertificates.svelte";
  let pageLoaded = false;
  $: searchvalue = "";
  $: active_deletes = [];
  export let current_runners = [];
  const runners_promise = RunnerService.runnerControllerGetAll().then((val) => {
    current_runners = val;
    pageLoaded = true;
  });
  $: selectedFilter_teams = null;
  $: selectedFilter = null;
  $: filter__teams = selectedFilter_teams || [];
  $: filter__orgs = selectedFilter || [];
  $: filterGroupIDs = filter__teams.concat(filter__orgs).map((i) => i.value);
  $: sponsoring_contracts_show = current_runners.some(
    (r) => r.is_selected === true
  );
  $: cards_show = current_runners.some((r) => r.is_selected === true);
  $: certificates_show = current_runners.some((r) => r.is_selected === true);
  $: generate_runners = current_runners.filter((r) => r.is_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);

  RunnerTeamService.runnerTeamControllerGetAll().then((val) => {
    teams = val;
  });
  RunnerOrganizationService.runnerOrganizationControllerGetAll().then((val) => {
    orgs = val;
  });
  // ===
  import { DataHandler, Datatable, Th, ThFilter } from "@vincjo/datatables";
  const handler = new DataHandler(current_runners, { rowsPerPage: 50 });
  const rows = handler.getRows();
</script>

{#if store.state.jwtinfo.userdetails.permissions.includes("RUNNER:GET")}
  {#await runners_promise}
    <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>
  {:then}
    <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>
              <input
                type="checkbox"
                class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
              />
            </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 {handler} orderBy="group">Gruppe</Th>
            <Th {handler} orderBy="distance">Distanz</Th>
            <th>{$_("action")}</th>
          </tr>
          <tr>
            <th />
            <ThFilter {handler} filterBy="id" />
            <ThFilter {handler} filterBy="firstname" />
            <ThFilter {handler} filterBy="middlename" />
            <ThFilter {handler} filterBy="lastname" />
            <ThFilter {handler} filterBy="group" />
            <th />
            <th />
          </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"
                />
              </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 />
              <!-- <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>
  {/await}
{/if}

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