<script lang="ts">
  import TableGenerator from './table/table-generator.svelte';
  import Loading from '$lib/navigation/loading.svelte';
  import type { ApiResponse, StaffLdb } from '@owlboard/ts-types';
  import { detailInit, defineDetail } from './train-detail';
  import TrainDetail from './train-detail.svelte';
  import { fetchStaffLdb } from './fetch';

  export let station: string;
  export let title: string | undefined = 'Loading...';
  export let error = {
    state: false,
    name: 'none'
  };

  let detail = detailInit();
  function hideDetail() {
    detail = detailInit();
  }
  function showDetail(rid: string, uid: string, tid: string) {
    detail = defineDetail(rid, uid, tid);
  }

  console.log(`Station: ${station}`);

  async function callFetch(station: string): Promise<StaffLdb> {
    const data = await fetchStaffLdb(station);
    if (data.data) {
      title = data.data.locationName;
      return data.data;
    }
    throw new Error('Unable to Fetch Data');
  }
</script>

{#key detail}
  {#if detail.show}
    <TrainDetail {detail} close={hideDetail} />
  {/if}
{/key}

{#await callFetch(station)}
  <!--<Loading />  Loading already appears, but I don't know where it is being imported from!!!-->
{:then data}
  {#if data}
    <p class="generatedTime">Updated: {new Date(data.generatedAt).toLocaleTimeString()}</p>
    {#if data.trainServices?.length}
      <TableGenerator services={data.trainServices} click={showDetail} />
    {/if}
    {#if data.busServices?.length}
      <img class="transport-mode" src="/images/transport-modes/bus.svg" alt="Bus services" /><br />
      <span class="table-head-text">Bus Services</span>
      <TableGenerator services={data.busServices} click={showDetail} />
    {/if}
    {#if data.ferryServices?.length}
      <img class="transport-mode" src="/images/transport-modes/ferry.svg" alt="Ferry services" /><br />
      <span class="table-head-text">Ferry Services</span>
      <TableGenerator services={data.ferryServices} click={showDetail} />
    {/if}
  {/if}
{:catch}
  Error Loading Data
{/await}

{#if error.state}
  {#if error.name === 'unauthorized'}
    <p>Error: {error.name.toLocaleUpperCase()}</p>
  {/if}
{/if}
