<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';
  import AlertBar from '../nrcc/alert-bar.svelte';

  export let station: string;
  export let title: string | undefined = 'Loading...';

  let errorDetail = {
    code: '',
    message: '',
  };
  let nrcc: string[] = [];

  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;
      if (data.data?.nrccMessages) {
        for (const msg of data.data.nrccMessages) {
          nrcc.push(msg.xhtmlMessage);
        }
      }
      return data.data;
    }
    errorDetail.code = data.obStatus.toString() || "UNKNOWN";
    errorDetail.message = data.obMsg || "An unknown error occoured";
    throw new Error('Unable to Fetch Data');
  }
</script>

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

{#await callFetch(station)}
  <Loading />
{: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 nrcc.length}
      <AlertBar alerts={nrcc} />
    {/if}
    <!-- NRCC Alerts are not available -->
  {/if}
{:catch}
  <h2>Error</h2>
  <p>ERR-CODE: {errorDetail.code}</p>
  <p>Message:<br>{errorDetail.message}</p>
{/await}

<style>
  .transport-mode {
    padding-top: 20px;
    height: 17px;
  }
  .table-head-text {
    color: white;
  }
</style>