<script lang="ts">
    import TableGenerator from "./table/table-generator.svelte";
    import Loading from "$lib/navigation/loading.svelte";
    import type { StaffLdb } from "@owlboard/ts-types";
    import { detailInit, defineDetail } from "./train-detail";
    import TrainDetail from "./train-detail.svelte";
    import { fetchStaffLdb } from "./fetch";
    import AlertBar from "../common/nrcc/alert-bar.svelte";
    import TimeBar from "$lib/navigation/TimeBar.svelte";
    import { onMount } from "svelte";
    import { IconBus, IconSailboat } from "@tabler/icons-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}`);

    let updatedTime: Date;

    async function callFetch(station: string): Promise<StaffLdb> {
        console.log("callFetch function called");
        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);
                }
                nrcc = nrcc; // Reassign to ensure Svelte reloads
            }
            if (data.data.generatedAt) {
                updatedTime = new Date(data.data.generatedAt);
            }
            return data.data;
        }
        errorDetail.code = data.obStatus.toString() || "UNKNOWN";
        errorDetail.message = data.obMsg || "An unknown error occoured";
        throw new Error("Unable to Fetch Data");
    }

    onMount(async () => {
        console.log("staff-ldb component mounted");
    });
</script>

{#if nrcc.length}
    <AlertBar alerts={nrcc} />
{/if}

<TimeBar bind:updatedTime />

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

{#await callFetch(station)}
    <Loading />
{:then data}
    {#if data}
        {#if data.trainServices?.length}
            <TableGenerator services={data.trainServices} click={showDetail} />
        {/if}
        {#if data.busServices?.length}
            <IconBus />
            <br />
            <span class="table-head-text">Bus Services</span>
            <TableGenerator services={data.busServices} click={showDetail} />
        {/if}
        {#if data.ferryServices?.length}
            <IconSailboat />
            <br>
            <span class="table-head-text">Ferry Services</span>
            <TableGenerator services={data.ferryServices} click={showDetail} />
        {/if}
    {/if}
{:catch}
    <h2>Error</h2>
    <p>ERR-CODE: {errorDetail.code}</p>
    <p>Message:<br />{errorDetail.message}</p>
{/await}

<style>
    .table-head-text {
        color: white;
    }
</style>
