<script lang="ts">
    import { apiGet } from "$lib/scripts/apiFetch";
    import type { ReasonCode } from "@owlboard/ts-types";

    export let code: string;
    export let type: string;

    async function getDelay(code: string): Promise<string | undefined> {
        const data = await getReason(code);
        if (data) {
            return data[0].lateReason || "This train has been delayed";
        }
    }

    async function getCancel(code: string): Promise<string | undefined> {
        const data = await getReason(code);
        if (data) {
            return data[0].cancReason || "This train has been cancelled";
        }
    }

    async function getReason(code: string): Promise<ReasonCode[] | undefined> {
        const apiString = `/api/v2/ref/reasonCode/${code}`;
        try {
            const apiRes = (await apiGet(apiString)) as ReasonCode[];
            return apiRes;
        } catch (err) {
            console.error("Unable to define reason code");
        }
    }
</script>

{#if type === "cancel"}
    {#await getCancel(code)}
        This train has been cancelled
    {:then reason}
        {reason}
    {:catch}
        This train has been cancelled
    {/await}
{:else if type === "delay"}
    {#await getDelay(code)}
        This train has been delayed
    {:then reason}
        {reason}
    {:catch}
        This train has been delayed
    {/await}
{/if}
