<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';

    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 = `https://owlboard.info/api/v2/timetable/train/${date}/${searchType}/${id}`
        const res = await fetch(url, options);
        isLoading = false;
        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;
        }
    } 

</script>

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

{#if error}
<Island>
  <p class="error">{errMsg}</p>
</Island>
{/if}

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

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