<script>
  import Header from '$lib/navigation/header.svelte';
  import Nav from '$lib/navigation/nav.svelte';
  import Island from '$lib/islands/island.svelte';
  import Loading from '$lib/navigation/loading.svelte';
  import { uuid } from '$lib/stores/uuid';
  import StylesToc from '$lib/train/styles-toc.svelte';
  import { getApiUrl } from '$lib/scripts/upstream';

  const title = 'PIS Finder';
  const variables = { title: 'Results' };
  let entryPIS = '';
  let entryStartCRS = '';
  let entryEndCRS = '';
  let data = [];
  let error = false;
  let errMsg = 'Unknown Error';
  let isLoading = false;

  async function findByStartEnd() {
    isLoading = true;
    const url = `${getApiUrl()}/api/v2/pis/byStartEnd/${entryStartCRS}/${entryEndCRS}`;
    await fetchData(url);
    isLoading = false;
  }

  async function findByPis() {
    isLoading = true;
    const url = `${getApiUrl()}/api/v2/pis/byCode/${entryPIS}`;
    await fetchData(url);
    isLoading = false;
  }

  async function fetchData(url) {
    const options = {
      method: 'GET',
      headers: {
        uuid: $uuid
      }
    };
    const res = await fetch(url, options); // Enable Auth
    if (res.status == 401) {
      errMsg = 'You must be logged in to the staff version';
      error = true;
      return false;
    } else if (res.status == 500) {
      errMsg = 'Server Error, try again later';
      error = true;
      return false;
    }
    const jsonData = await res.json();
    if (jsonData.ERROR == 'offline') {
      errMsg = 'Connection error, check your internet connection and try again';
      error = true;
      return false;
    }
    data = jsonData;
  }

  async function reset() {
    data = [];
    error = false;
    entryPIS = '';
    entryStartCRS = '';
    entryEndCRS = '';
  }
</script>

<Header {title} />

{#if isLoading}
  <Loading />
{/if}

{#if error}
  <Island {variables}>
    <p class="error">{errMsg}</p>
  </Island>
{:else if data.length}
  <Island {variables}>
    <table>
      <tr>
        <th class="toc">TOC</th>
        <th class="code">Code</th>
        <th class="stops">Stops</th>
      </tr>
      {#each data as item}
        <tr>
          <td class="toc toc-data"><StylesToc toc={item.toc || '-'} /></td>
          <td class="code">{item.code}</td>
          <td class="stops stops-data">{item.stops.join('  ')}</td>
        </tr>
      {/each}
    </table>
  </Island>
{:else}
  <p>To search by headcode use the Train Finder on the homepage</p>
  <p>This feature is only supported for GWR West & Sleeper services</p>
  <p class="label">Find By Start/End CRS:</p>
  <form on:submit={findByStartEnd}>
    <input type="text" maxlength="3" autocomplete="off" placeholder="Start" bind:value={entryStartCRS} />
    <input type="text" maxlength="3" autocomplete="off" placeholder="End" bind:value={entryEndCRS} />
    <br />
    <button type="submit">Search</button>
  </form>

  <p class="label">Find By PIS Code:</p>
  <form on:submit={findByPis}>
    <input type="number" max="9999" autocomplete="off" placeholder="PIS" bind:value={entryPIS} />
    <br />
    <button type="submit">Search</button>
  </form>
{/if}
<button id="reset" type="reset" on:click={reset}>Reset</button>
<Nav />

<style>
  p {
    margin-left: 10px;
    margin-right: 10px;
  }
  .label {
    font-weight: 600;
    color: var(--main-text-color);
  }
  input {
    border: none;
    border-radius: 50px;
    font-family: urwgothic, sans-serif;
    text-align: center;
    text-transform: uppercase;
    width: 30%;
    max-width: 250px;
    height: 30px;
    font-size: 16px;
    margin-bottom: 15px;
    box-shadow: var(--box-shadow);
  }
  button {
    border: none;
    border-radius: 50px;
    font-family: urwgothic, sans-serif;
    width: 25%;
    max-width: 175px;
    margin: 0px;
    margin-left: 10px;
    margin-right: 10px;
    height: 30px;
    background-color: var(--island-bg-color);
    color: white;
    font-size: 16px;
    box-shadow: var(--box-shadow);
  }
  table {
    width: 100%;
    margin: auto;
    color: white;
  }
  td {
    padding-top: 5px;
    padding-bottom: 5px;
  }
  .toc {
    width: 15%;
  }
  .code {
    width: 20%;
  }
  .toc-data {
    text-transform: uppercase;
  }
  .stops-data {
    text-align: left;
    font-family: firamono, monospace;
    text-transform: uppercase;
  }
  .error {
    color: white;
  }
  #reset {
    margin: 25px;
  }
</style>
