<script>
  import axios from "axios";
  import { _ } from "svelte-i18n";
  import { apikey, api_endpoint, page, stationinfo } from "./store.js";
  function init(el) {
    el.focus();
  }
  let lastscan_error = "";
  let lastscan_time = "";
  let lastscan_laptime = "";
  let lastscan_totaldistance = "";
  let lastscan_valid = true;
  let card = "";
  // live clock at the top
  let time = new Date();
  $: hours = (time.getHours() + "").padStart(2, "0");
  $: minutes = (time.getMinutes() + "").padStart(2, "0");
  $: seconds = (time.getSeconds() + "").padStart(2, "0");
  setInterval(() => {
    time = new Date();
  }, 1000);
</script>

<div class="min-h-screen">
  <div class="bg-white shadow p-2">
    <div class="flex flex-wrap -mx-1 overflow-hidden">
      <div class="my-1 px-1 w-1/3 overflow-hidden text-center self-center">
        <img src="/favicon.png" alt="" class="h-14 mx-auto" />
      </div>

      <div class="my-1 px-1 w-1/3 overflow-hidden text-center self-center">
        Lauf Für Kaya! Scan
      </div>

      <div class="my-1 px-1 w-1/3 overflow-hidden text-center self-center">
        {JSON.parse($stationinfo).track.name} - #{JSON.parse($stationinfo).track
          .id} - {JSON.parse($stationinfo).track.distance}m
      </div>
    </div>
  </div>

  <h1 class="mr-6 text-7xl font-semibold text-center text-gray-900 font-mono">
    {hours}:{minutes}:{seconds}
  </h1>
  <section class="px-4 py-2 mx-auto max-w-7xl">
    <div class="mx-auto space-y-5 w-full md:w-1/2">
      {#if lastscan_error}
        <div
          class="text-white px-6 py-4 border-0 rounded relative bg-red-500 mt-2"
        >
          <span class="inline-block align-middle">
            <b class="capitalize">Error!</b><br />{lastscan_error}
          </span>
        </div>
      {/if}
      <form
        onsubmit="event.preventDefault();"
        on:submit={() => {
          if (card === "cnf") {
            page.set("settings");
          } else {
            card = parseInt(card);
            lastscan_error = "";
            axios
              .request({
                method: "POST",
                url: $api_endpoint + "api/scans/trackscans",
                headers: { Authorization: "Bearer " + $apikey },
                data: { card },
              })
              .then((response) => {
                const time = new Date();
                const hours = (time.getHours() + "").padStart(2, "0");
                const minutes = (time.getMinutes() + "").padStart(2, "0");
                const seconds = (time.getSeconds() + "").padStart(2, "0");
                lastscan_time = hours + ":" + minutes + ":" + seconds;
                response.data.lapTime =
                  Math.floor(response.data.lapTime / 60) +
                  "min " +
                  (Math.floor(response.data.lapTime % 60) + "").padStart(
                    2,
                    "0"
                  ) +
                  "s";
                lastscan_laptime = response.data.lapTime;
                lastscan_valid = response.data.valid;
                lastscan_totaldistance =
                  Math.floor(response.data.runner.distance / 1000) +
                  "km " +
                  (
                    Math.floor(response.data.runner.distance % 1000) + ""
                  ).padStart(3, "0") +
                  "m";
              })
              .catch((e) => {
                lastscan_error = e.response.data.message;
              });
          }
          card = "";
        }}
      >
        <label class="block">
          <span class="block mb-1 text-xs font-medium text-gray-700"
            >{$_("runner_card")}</span
          >
          <input
            class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mt-1 leading-tight focus:outline-none focus:shadow-outline"
            type="text"
            placeholder="123456789"
            required
            use:init
            bind:value={card}
          />
        </label>
        {#if lastscan_totaldistance}
          <div class="w-full text-center items-center">
            {#if !lastscan_valid || lastscan_error}
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                stroke-width="1.5"
                stroke="currentColor"
                class="w-30 h-30 text-center mx-auto text-red-600"
                viewBox="5.25 5.25 13.5 13.5"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            {:else}
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                stroke-width="1.5"
                stroke="currentColor"
                class="w-30 h-30 text-center mx-auto text-green-600"
                viewBox="3.75 4.5 16.5 15"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  d="m4.5 12.75 6 6 9-13.5"
                />
              </svg>
            {/if}
          </div>
          <h1 class="text-2xl font-bold text-center">{$_("total-distance")}</h1>
          <h1 class="text-6xl font-bold text-center">
            {lastscan_totaldistance}
          </h1>
          <h1 class="text-2xl font-bold text-center">{$_("lap-time")}</h1>
          <h1 class="text-6xl font-bold text-center">{lastscan_laptime}</h1>
          <h1 class="text-2xl font-bold text-center">{$_("last-scan")}</h1>
          <h1 class="text-5xl font-bold text-center">{lastscan_time}</h1>
        {:else}
          <h1 class="text-3xl font-bold text-center">
            {$_("please_scan_a_card")}
          </h1>
        {/if}
        <button type="submit" class="hidden">{$_("scan")}</button>
      </form>
    </div>
  </section>
</div>
