<script>
  import { _ } from "svelte-i18n";
  import { ScanService, TrackService } from "@odit/lfk-client-js";
  import store from "../../store";
  import {
    createSvelteTable,
    flexRender,
    getCoreRowModel,
    getFilteredRowModel,
    getPaginationRowModel,
    getSortedRowModel,
    renderComponent,
  } from "@tanstack/svelte-table";
  import { onMount } from "svelte";
  import { writable } from "svelte/store";

  import TableBottom from "../shared/TableBottom.svelte";
  import TableHeader from "../shared/TableHeader.svelte";
  import ScansEmptyState from "./ScansEmptyState.svelte";
  import InputElement from "../shared/InputElement.svelte";
  import TableActions from "../shared/TableActions.svelte";
  import { runnerFilter, statusFilter } from "../shared/tablefilters";
  import CardRunner from "../cards/CardRunner.svelte";
  import ScanValid from "./ScanValid.svelte";
  import DeleteScanModal from "./DeleteScanModal.svelte";
  import toast from "svelte-french-toast";

  $: selectedScans =
    $table?.getSelectedRowModel().rows.map((row) => row.original) || [];
  $: selected =
    $table?.getSelectedRowModel().rows.map((row) => row.index) || [];

  $: active_delete = undefined;
  $: dataLoaded = false;
  export let current_scans = [];
  export const addScans = (scans) => {
    current_scans = current_scans.concat(...scans);
    options.update((options) => ({
      ...options,
      data: current_scans,
    }));
  };

  let allTracks = [];
  TrackService.trackControllerGetAll().then((val) => {
    allTracks = val;
  });
  function format_laptime(laptime) {
    if (laptime == 0 || laptime == null) {
      return $_("first-scan-of-the-day");
    }
    laptime = Number(laptime);
    const h = Math.floor(laptime / 3600);
    const m = Math.floor((laptime % 3600) / 60);
    const s = Math.floor((laptime % 3600) % 60);

    const hDisplay = h > 0 ? h + (h == 1 ? "h, " : "h, ") : "";
    const mDisplay = m > 0 ? m + (m == 1 ? "min, " : "min, ") : "";
    const sDisplay = s > 0 ? s + (s == 1 ? "s" : "s") : "";
    return hDisplay + mDisplay + sDisplay;
  }

  const columns = [
    {
      accessorKey: "id",
      header: () => "id",
      filterFn: `equalsString`,
    },
    {
      accessorKey: "runner",
      header: () => $_("runner"),
      cell: (info) => {
        return renderComponent(CardRunner, { runner: info.getValue() });
      },
      filterFn: `runner`,
    },
    {
      accessorKey: "lapTime",
      header: () => $_("laptime"),
      cell: (info) => {
        return format_laptime(info.getValue());
      },
      enableColumnFilter: false,
    },
    {
      accessorKey: "timestamp",
      header: () => $_("timestamp"),
      cell: (info) => {
        return new Date(parseInt(info.getValue()) * 1000).toLocaleString(
          { language: "de-DE" },
          {
            day: "2-digit",
            month: "2-digit",
            year: "numeric",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
          }
        );
      },
      enableColumnFilter: false,
    },
    {
      accessorKey: "distance",
      header: () => $_("distance"),
      cell: (info) => {
        if (info.getValue() < 1000) {
          return `${info.getValue()}m`;
        }
        return `${(info.getValue() / 1000).toFixed(1)}km`;
      },
      enableColumnFilter: false,
    },
    {
      accessorKey: "track",
      header: () => $_("track"),
      cell: (info) => {
        const track = info.getValue();
        return track?.name || "?";
      },
      enableColumnFilter: true,
    },
    {
      accessorKey: "valid",
      cell: (info) => {
        return renderComponent(ScanValid, { valid: info.getValue() });
      },
      header: () => $_("status"),
      filterFn: `status`,
    },
    {
      accessorKey: "actions",
      header: () => $_("action"),
      cell: (info) => {
        return renderComponent(TableActions, {
          detailsLink: `./${info.row.original.id}`,
          deleteAction: () => {
            active_delete =
              current_scans[
                current_scans.findIndex((r) => r.id == info.row.original.id)
              ];
          },
          deleteEnabled:
            store.state.jwtinfo.userdetails.permissions.includes("SCAN:DELETE"),
        });
      },
      enableColumnFilter: false,
      enableSorting: false,
    },
  ];
  const options = writable({
    data: [],
    columns: columns,
    initialState: {
      pagination: {
        pageSize: 50,
      },
    },
    filterFns: {
      runner: runnerFilter,
      status: statusFilter,
    },
    enableRowSelection: true,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
  });
  const table = createSvelteTable(options);
  async function deleteScan(scan_id) {
    await ScanService.scanControllerRemove(scan_id, true);
    current_scans = current_scans.filter((r) => r.id !== scan_id);
    options.update((options) => ({
      ...options,
      data: current_scans,
    }));
    toast($_("scan-deleted"));
  }

  onMount(async () => {
    let page = 0;
    let pagesize = 500;
    while (page >= 0) {
      const scans = await ScanService.scanControllerGetAll(page, pagesize);
      if (scans.length == 0) {
        page = -2;
      }

      current_scans = current_scans.concat(...scans);
      options.update((options) => ({
        ...options,
        data: current_scans,
      }));

      dataLoaded = true;
      page++;
    }
  });
</script>

<DeleteScanModal
  delete_scan={active_delete}
  modal_open={active_delete != undefined}
  on:delete={(event) => {
    deleteScan(event.detail.id);
  }}
/>
{#if store.state.jwtinfo.userdetails.permissions.includes("SCAN: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">{$_("scans-are-being-loaded")}</p>
      <p class="text-sm">{$_("this-might-take-a-moment")}</p>
    </div>
  {:else if current_scans.length === 0}
    <ScansEmptyState />
  {:else}
    {#if selected.length > 0}
      <button
        type="button"
        class="w-full justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:w-auto sm:text-sm inline-flex"
        id="options-menu"
        on:click={async () => {
          const prom = [];
          for (const scan of selectedScans) {
            prom.push(ScanService.scanControllerRemove(scan.id, true));
          }
          await Promise.all(prom);
          for (const scan of selectedScans) {
            current_scans = current_scans.filter((r) => r.id !== scan.id);
          }
          options.update((options) => ({
            ...options,
            data: current_scans,
          }));
          $table.resetRowSelection();
          toast.success($_("scan-deleted"));
        }}
      >
        {$_("delete-scans")}
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          stroke-width="1.5"
          stroke="currentColor"
          class="w-5 h-5"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"
          />
        </svg>
      </button>
    {/if}
    <div class="overflow-x-auto">
      <table class="w-full">
        <thead class="border-b border-gray-400">
          {#each $table.getHeaderGroups() as headerGroup}
            <tr class="select-none">
              <th class="inset-y-0 left-0 px-4 py-2 text-left w-px">
                <InputElement
                  type="checkbox"
                  checked={$table.getIsAllRowsSelected()}
                  indeterminate={$table.getIsSomeRowsSelected()}
                  on:change={() => $table.toggleAllRowsSelected()}
                />
              </th>
              {#each headerGroup.headers as header}
                <TableHeader {header} />
              {/each}
            </tr>
          {/each}
        </thead>
        <tbody>
          {#each $table.getRowModel().rows as row}
            <tr class="odd:bg-white even:bg-gray-100">
              <td class="inset-y-0 left-0 px-4 py-2 text-center w-px">
                <InputElement
                  type="checkbox"
                  checked={row.getIsSelected()}
                  on:change={() => row.toggleSelected()}
                />
              </td>
              {#each row.getVisibleCells() as cell}
                <td>
                  <svelte:component
                    this={flexRender(
                      cell.column.columnDef.cell,
                      cell.getContext()
                    )}
                  />
                </td>
              {/each}
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
    <TableBottom {table} {selected} />
  {/if}
{/if}

<style>
  table tbody tr td:nth-child(2) {
    font-family: monospace;
  }
</style>
