<script lang="ts">
    import Header from "$lib/navigation/header.svelte";
    import Island from "$lib/islands/island.svelte";
    import Nav from "$lib/navigation/nav.svelte";
    import { uuid } from "$lib/stores/uuid";

    import { onMount } from "svelte";
    import TrainDetail from "$lib/train/train-detail.svelte";
    import { getApiUrl } from "$lib/scripts/upstream";
    import toast from "svelte-french-toast";
    import TimeBar from "$lib/navigation/TimeBar.svelte";
    import { IconArrowLeft, IconArrowRight, IconCheck } from "@tabler/icons-svelte";
    import Error from "../+error.svelte";

    let title = "Timetable Results";
    let id = "";
    let data = [];
    let error = false;
    let errMsg = "";

    let formattedDate = new Date().toISOString().split('T')[0];

    $: {
        if (id) {
            title = id.toUpperCase();
        } else {
            title = "Querying Timetable";
        }
    }

    async function getHeadcode() {
        return new URLSearchParams(window.location.search).get("headcode");
    }

    function incrementDate() {
        let dateInput = new Date(formattedDate)
        dateInput.setDate(dateInput.getDate() + 1);
        formattedDate = dateInput.toISOString().split('T')[0];
    }

    function decrementDate() {
        let dateInput = new Date(formattedDate)
        dateInput.setDate(dateInput.getDate() - 1);
        formattedDate = dateInput.toISOString().split('T')[0];
    }

    onMount(async () => {
        id = (await getHeadcode()) || "";
        load();

        toast("Registration soon required for timetable features.\n\nClick 'Register' in the menu.", {
            duration: 3000,
        });

    });

    function load() {
        error = false;
        const selectedDate = new Date(formattedDate);
        const currentDate = new Date();
        const difference: number = currentDate.getTime() - selectedDate.getTime();
        const differenceDays: number = difference / (1000 * 60 * 60 * 24)
        if (differenceDays > 7) {
            toast.error("Timetable data is not available for dates older than a week")
            return
        }

        toast.promise(
            fetchData(id),
            {
                loading: 'Searching Timetable',
                success: 'Done',
                error: 'Error'
            }
        )
    }

    async function fetchData(id = "") {
        data = [];
        const searchType = "headcode";
        const options = {
            method: "GET",
            headers: {
                uuid: $uuid,
            },
        };
        const url = `${getApiUrl()}/api/v2/timetable/train/${formattedDate}/${searchType}/${id}`;
        try {
            const res = await fetch(url, options);
            if (res.status == 200) {
                let services = await res.json();
                if (!services.length) {
                    error = true;
                    errMsg = "No services found";
                    return Promise.reject(new Error(errMsg));
                }
                data = services
            } else if (res.status === 401) {
                error = true;
                errMsg = "You must be logged into the staff version for this feature";
                return Promise.reject(new Error(errMsg));
            } else {
                error = true;
                errMsg = "Unable to connect, check your connection and try again";
                return Promise.reject(new Error(errMsg));
            }
        } catch (err) {
            error = true;
            errMsg = "Connection error, try again later";
            return Promise.reject(new Error(errMsg));
        }
    }
</script>

<Header {title} />
<TimeBar updatedTime={undefined} />
<div id="dateSelector">
    <button on:click={decrementDate}><IconArrowLeft /></button>
    <input 
        type="date" 
        id="dateInput" 
        bind:value={formattedDate}
    />
    <button on:click={incrementDate}><IconArrowRight /></button>
    <button on:click={load}><IconCheck /></button>
</div>
{#if error}
    <Island>
        <p style="font-weight:600">{errMsg}</p>
    </Island>
{/if}

{#each data as service}
    {#if service}
        <TrainDetail {service} date={new Date(formattedDate)} />
    {/if}
{/each}

<Nav />

<style>
    p {
        color: white;
        font-size: 18px;
        font-weight: 600;
    }

    #dateInput {
        height: 25px;
        transform: translateY(-8px) translateX(20px);
    }
    button {
        background: none;
        border: none;
        color: white;
        transform: translateX(20px);
    }
</style>
