<script>
  import { _, json } from "svelte-i18n";
  import Toastify from "toastify-js";
  import TracksEmptyState from "./TracksEmptyState.svelte";
  import { TrackService } from "@odit/lfk-client-js";
  const tracks_promise = TrackService.trackControllerGetAll();
  import { getlang } from "./datatable_i18n";
  import { Grid, html } from "gridjs";
  import { tracks as tracksstore } from "../store.js";
  $: trackscache = [];
  $: blocked = [];
  let table;
  let datatable;
  let datatable_inited = false;
  tracksstore.subscribe((val) => {
    trackscache = val;
    setTimeout(() => {
      if (val.length > 0) {
        renderdatatable();
      }
    }, 100);
  });
  tracks_promise.then((data) => {
    tracksstore.set(data);
  });
  window.track__edit_cancel = () => renderdatatable();
  window.track__edit_save = () => {
    const trackid = parseInt(window.event.target.getAttribute("data-trackid"));
    if (blocked.includes(trackid)) {
      //
    } else {
      blocked.push(trackid);
      const elem = document.querySelector(
        `[data-id="triggered_table_actions_${trackid}"]`
      ).parentNode.parentNode.parentNode;
      Toastify({
        text: "Track is being updated...",
        duration: 500,
      }).showToast();
      TrackService.trackControllerPut(trackid, {
        id: trackid,
        name: elem.childNodes[0].childNodes[0].value,
        distance: parseInt(elem.childNodes[1].childNodes[0].value),
        minimumLapTime: parseInt(elem.childNodes[2].childNodes[0].value),
      })
        .then((r) => {
          Toastify({
            text: "Track was updated!",
            backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
            duration: 1000,
          }).showToast();
          blocked = blocked.filter((e) => e !== trackid);
          document
            .querySelector(`[data-id="default_table_actions_${trackid}"]`)
            .classList.remove("hidden");
          document
            .querySelector(`[data-id="triggered_table_actions_${trackid}"]`)
            .classList.add("hidden");
          //
          elem.childNodes[0].innerHTML = `<td data-column-id="trackName" class="gridjs-td">${elem.childNodes[0].childNodes[0].value}</td>`;
          elem.childNodes[1].innerHTML = `<td data-column-id="trackName" class="gridjs-td">${elem.childNodes[1].childNodes[0].value}</td>`;
          elem.childNodes[2].innerHTML = `<td data-column-id="trackName" class="gridjs-td">${elem.childNodes[2].childNodes[0].value}</td>`;
        })
        .catch((err) => {
          console.error(err);
        });
    }
  };
  window.track__delete_handler = () => {
    const trackid = parseInt(window.event.target.getAttribute("data-trackid"));
    document
      .querySelector(`[data-id="default_table_actions_${trackid}"]`)
      .classList.add("hidden");
    document
      .querySelector(`[data-id="deleteconfirmation_table_actions_${trackid}"]`)
      .classList.remove("hidden");
  };
  window.track__delete_cancel = () => {
    const trackid = parseInt(window.event.target.getAttribute("data-trackid"));
    document
      .querySelector(`[data-id="default_table_actions_${trackid}"]`)
      .classList.remove("hidden");
    document
      .querySelector(`[data-id="deleteconfirmation_table_actions_${trackid}"]`)
      .classList.add("hidden");
  };
  window.track__delete_confirm = () => {
    const trackid = parseInt(window.event.target.getAttribute("data-trackid"));
    TrackService.trackControllerRemove(trackid)
      .then(() => {
        const newStoreVal = trackscache.filter((obj) => obj.id !== trackid);
        tracksstore.set(newStoreVal);
        renderdatatable();
      })
      .catch((err) => {
        console.log(err);
      });
  };
  window.track__edit_handler = () => {
    const trackid = parseInt(window.event.target.getAttribute("data-trackid"));
    document
      .querySelector(`[data-id="default_table_actions_${trackid}"]`)
      .classList.add("hidden");
    document
      .querySelector(`[data-id="triggered_table_actions_${trackid}"]`)
      .classList.remove("hidden");
    const elem = document.querySelector(
      `[data-id="triggered_table_actions_${trackid}"]`
    ).parentNode.parentNode.parentNode;
    const trackname = elem.childNodes[0].textContent;
    const tracklength = parseInt(elem.childNodes[1].textContent);
    const trackmintime = parseInt(elem.childNodes[2].textContent);
    elem.childNodes[0].innerHTML = `<input type="text" value="${trackname}" name="trackname" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 rounded-md p-2">`;
    elem.childNodes[1].innerHTML = `<input type="text" value="${tracklength}" name="tracklength" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 rounded-md p-2">`;
    elem.childNodes[2].innerHTML = `<input type="text" value="${trackmintime}" name="trackmintime" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm rounded-l-md sm:text-sm border-gray-300 border bg-gray-50 text-gray-500 rounded-md p-2">`;
  };
  //
  function renderdatatable() {
    let tabledata = [];
    trackscache.forEach((track) => {
      tabledata.push([
        track.name,
        track.distance,
        track.minimumLapTime || 0,
        html(`
        <div class="hidden" data-id="triggered_table_actions_${track.id}">
          <button class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-400 text-base font-medium text-white sm:w-auto sm:text-sm" data-trackid="${track.id}" onclick="track__edit_save()">Save</button>
          <button class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-500 text-base font-medium text-white sm:w-auto sm:text-sm" data-trackid="${track.id}" onclick="track__edit_cancel()">Cancel</button>
        </div>
        <div data-id="default_table_actions_${track.id}">
          <button class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-gray-400 text-base font-medium text-white sm:w-auto sm:text-sm" data-trackid="${track.id}" onclick="track__edit_handler()">Edit</button>
          <button class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-500 text-base font-medium text-white sm:w-auto sm:text-sm" data-trackid="${track.id}" onclick="track__delete_handler()">Delete</button>
        </div>
        <div class="hidden" data-id="deleteconfirmation_table_actions_${track.id}">
          <button class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-gray-400 text-base font-medium text-white sm:w-auto sm:text-sm" data-trackid="${track.id}" onclick="track__delete_cancel()">Cancel</button>
          <button class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-500 text-base font-medium text-white sm:w-auto sm:text-sm" data-trackid="${track.id}" onclick="track__delete_confirm()">Confirm</button>
        </div>
      `),
      ]);
    });

    if (datatable_inited === false) {
      datatable = new Grid({
        columns: [
          $_("track-name"),
          $_("track-length-in-m"),
          $_("minimum-lap-time-in-s"),
          $_("action"),
        ],
        language: getlang($json("datatable")),
        sort: true,
        search: { enabled: true },
        data: tabledata,
        pagination: {
          enabled: true,
          limit: 25,
          summary: false,
        },
      }).render(table);
      datatable_inited = true;
    } else {
      datatable.updateConfig({ data: tabledata }).forceRender();
    }
  }
</script>

{#if trackscache.length > 0}
  <div bind:this={table} />
{/if}
{#await tracks_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">{$_('track-data-is-being-loaded')}</p>
    <p class="text-sm">{$_('this-might-take-a-moment')}</p>
  </div>
{:then}
  {#if trackscache.length === 0}
    <TracksEmptyState />
  {/if}
{:catch error}
  <div class="text-white px-6 py-4 border-0 rounded relative mb-4 bg-red-500">
    <span class="inline-block align-middle mr-8">
      <b class="capitalize">{$_('general_promise_error')}</b>
      {error}
    </span>
  </div>
{/await}
