<script>
    import { getApiUrl } from "$lib/scripts/upstream";
    import { uuid } from "$lib/stores/uuid";

    export let code = "";
    export let type = "";

    async function getDelay(code = "") {
        console.log(`Fetching delay reason ${code}`);
        const data = await getReason(code);
        return data[0].lateReason || "This train has been delayed";
    }

    async function getCancel(code = "") {
        console.log(`Fetching cancel reason ${code}`);
        const data = await getReason(code);
        return data[0].cancReason || "This train has been cancelled";
    }

    async function getReason(code = "") {
        const url = `${getApiUrl()}/api/v2/ref/reasonCode/${code}`;
        const options = {
            method: "GET",
            headers: {
                uuid: $uuid,
            },
        };
        const res = await fetch(url, options);
        return await res.json();
    }
</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}
