<script>
  import Header from '$lib/navigation/header.svelte';
  import Loading from '$lib/navigation/loading.svelte';
  import Island from '$lib/islands/island.svelte';
  import Nav from '$lib/navigation/nav.svelte';
  import { uuid } from '$lib/stores/uuid';

  import { onMount } from 'svelte';
  import TrainDetail from '$lib/train/train-detail.svelte';
  import { getApiUrl } from '$lib/scripts/upstream';

  let title = 'Timetable Results';
  let id = '';
  let data = [];
  let isLoading = true;
  let error = false;
  let errMsg = '';

  $: {
    if (id) {
      title = id.toUpperCase();
    } else {
      title = 'Querying Timetable';
    }
  }

  async function getHeadcode() {
    return new URLSearchParams(window.location.search).get('headcode');
  }

  onMount(async () => {
    isLoading = true;
    id = (await getHeadcode()) || '';
    const res = await fetchData(id);
    if (res) {
      data = res;
      if (!data.length) {
        error = true;
        errMsg = 'No services found';
      }
    }
    isLoading = false;
  });

  async function fetchData(id = '') {
    const date = 'now';
    const searchType = 'headcode';
    const options = {
      method: 'GET',
      headers: {
        uuid: $uuid
      }
    };
    const url = `${getApiUrl()}/api/v2/timetable/train/${date}/${searchType}/${id}`;
    try {
      const res = await fetch(url, options);
      if (res.status == 200) {
        return await res.json();
      } else if (res.status === 401) {
        error = true;
        errMsg = 'You must be logged into the staff version for this feature';
        return false;
      } else {
        error = true;
        errMsg = 'Unable to connect, check your connection and try again';
        return false;
      }
    } catch (err) {
      error = true;
      errMsg = 'Connection error, try again later';
    }
    isLoading = false;
  }
</script>

<Header {title} />
<div id="whitespace" />

{#if error}
  <Island>
    <p style="font-weight:600">{errMsg}</p>
  </Island>
{/if}

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

{#each data as service}
  {#if service}
    <TrainDetail {service} />
  {/if}
{/each}

<Nav />

<style>
  #whitespace {
    height: 15px;
  }
  p {
    color: white;
    font-size: 18px;
    font-weight: 600;
  }
</style>
