<script>
    import Header from '$lib/navigation/header.svelte'
    import Nav from '$lib/navigation/nav.svelte'
    
    import { onMount } from 'svelte'

    let title = "Timetable Results"
    let id = ""
    let data = [];

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

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

    onMount(async () => {
        id = await getHeadcode() || "";
        data = await fetchData(id);
    })

    async function fetchData(id = "") {
        const date = 'now';
        const searchType = 'headcode'
        const url = `https://owlboard.info/api/v2/timetable/train/${date}/${searchType}/${id}`
        const res = await fetch(url);
        return await res.json();
    } 

</script>
 
<svelte:head>
   <title>OwlBoard {title}</title>
</svelte:head>

<Header {title} />
 
{#each data as service}
  {#if service.stops[0]['publicDeparture']}
    <h2>GW: {service.stops[0]['publicDeparture']} {service.stops[0]['tiploc']} to {service.stops[service['stops'].length -1]['tiploc']}</h2>
    <p>PIS: {service.pis}</p>
    <table>
      <tr>
        <th>Location</th>
        <th>Sch Arr.</th>
        <th>Sch Dep.</th>
      </tr>
    {#each service.stops as stop}
      {#if stop.publicArrival || stop.publicDeparture}
        <tr>  
          <td>{stop.tiploc}</td>
          <td>{stop.publicArrival || '-'}</td>
          <td>{stop.publicDeparture || '-'}</td>
        </tr>
      {/if}
    {/each}
    </table>
  {:else}
    <h2>GW: {service.stops[0]['wttDeparture']} {service.stops[0]['tiploc']} to {service.stops[service['stops'].length -1]['tiploc']}</h2>
    <p>PIS: {service.pis}</p>
    <table>
      <tr>
        <th>Location</th>
        <th>Sch Arr.</th>
        <th>Sch Dep.</th>
      </tr>
    {#each service.stops as stop}
      <tr>
        <td>{stop.tiploc}</td>
        <td>{stop.wttArrival}</td>
        <td>{stop.wttDeparture}</td>
      </tr>
    {/each}
    </table>
  {/if}
{/each}
 
<Nav />

<style>
  h2 {
    margin-top: 50px;
  }
  p {
    color: white;
    font-size: 20px;
    font-weight: 600;
  }
  table {
    margin: auto;
    color: white;
    font-size: 20px;
  }
  th, td {
    padding-left: 8px;
    padding-right: 8px;
  }
</style>