<script lang="ts">
    import Header from "$lib/navigation/header.svelte";
    import Nav from "$lib/navigation/nav.svelte";
    import { uuid } from "$lib/stores/uuid";
    import StylesToc from "$lib/train/styles-toc.svelte";
    import { getApiUrl } from "$lib/scripts/upstream";
    import toast from "svelte-french-toast";
    import { onMount } from "svelte";
    import type { OB_Pis_FullObject } from "@owlboard/ts-types";
    import Card from "$lib/cards/Card.svelte";
    import type { CardConfig } from "$lib/cards/Card.types";
    import FindByHeadcodeCard from "$lib/cards/FindByHeadcodeCard.svelte";

    const title = "PIS Finder";
    let entryPIS = "";
    let entryStartCRS = "";
    let entryEndCRS = "";
    let data: OB_Pis_FullObject[] = [];
    let error = false;
    let errMsg = "Unknown Error";

    async function findByStartEnd() {
        const url = `${getApiUrl()}/api/v2/pis/byStartEnd/${entryStartCRS}/${entryEndCRS}`;
        await fetchData(url);
    }


    async function findByPis() {
        const url = `${getApiUrl()}/api/v2/pis/byCode/${entryPIS}`;
        await fetchData(url);
    }

    async function fetchData(url: string) {
        const options = {
            method: "GET",
            headers: {
                uuid: $uuid,
            },
        };
        const res = await fetch(url, options); // Enable Auth
        if (res.status == 401) {
            errMsg = "You must be logged in to the staff version";
            toast.error("You must be registered");
            error = true;
            return false;
        } else if (res.status == 500) {
            errMsg = "Server Error, try again later";
            toast.error("Server Error.", { duration: 7500 });
            error = true;
            return false;
        }
        const jsonData = await res.json();
        if (jsonData.ERROR == "offline") {
            errMsg = "Connection error, check your internet connection and try again";
            toast.error("You are offline.");
            error = true;
            return false;
        }
        data = jsonData;
        let count = data.length;
        if (!count) {
            toast.error("No PIS Codes found.");
        } else {
            toast.success(`${count} PIS Codes found`);
        }
    }

    async function reset() {
        data = [];
        error = false;
        entryPIS = "";
        entryStartCRS = "";
        entryEndCRS = "";
    }

    onMount(() => {
        if ($uuid == null || $uuid == "") {
        toast("You must register to see results", {
            duration: 3000,
        });
        }
    });

    const resultsCard: CardConfig = {
        title: "Results",
        showHelp: false,
        helpText: "",
        showRefresh: false,
        onRefresh: ()=>{},
        refreshing: false
    }
    const errorCard: CardConfig = {
        title: "Error",
        showHelp: true,
        helpText: "There was an error searching for PIS Codes",
        showRefresh: false,
        onRefresh: () => {},
        refreshing: false,
    }
    const findByStartEndCard: CardConfig = {
        title: "Find by Start/End CRS",
        showHelp: true,
        helpText: "Enter a start and end CRS Code",
        showRefresh: false,
        onRefresh: () => {},
        refreshing: false,
    }
    const findByPisCodeCard: CardConfig = {
        title: "Find by PIS Code",
        showHelp: true,
        helpText: "Enter a PIS Code to see its details. (Four digits)",
        showRefresh: false,
        onRefresh: () => {},
        refreshing: false,
    }
</script>

<Header {title} />

{#if error}
    <Card config={errorCard}>
        <p class="error">{errMsg}</p>
    </Card>
{:else if data.length}
    <Card config={resultsCard}>
        <table>
            <tr>
                <th class="toc">TOC</th>
                <th class="code">Code</th>
                <th class="stops">Stops</th>
            </tr>
            {#each data as item}
                <tr>
                    <td class="toc toc-data"><StylesToc toc={item.toc || "-"} /></td>
                    <td class="code">{item.code}</td>
                    <td class="stops stops-data">{item.stops.join("  ")}</td>
                </tr>
            {/each}
        </table>
    </Card>
    <button id="reset" type="reset" on:click={reset}>Reset</button>
{:else}
    <FindByHeadcodeCard />
    <Card config={findByStartEndCard}>
    <form on:submit={findByStartEnd}>
        <input type="text" maxlength="3" pattern="^[A-Za-z]+$" autocomplete="off" placeholder="Start" required bind:value={entryStartCRS} />
        <input type="text" maxlength="3" pattern="^[A-Za-z]+$" autocomplete="off" placeholder="End" required bind:value={entryEndCRS} />
        <br />
        <button type="submit">Search</button>
        <button type="reset">Clear</button>
    </form>
    </Card>
    <Card config={findByPisCodeCard}>
      <form on:submit={findByPis}>
        <input type="text" maxlength="4" pattern="^\d+$" autocomplete="off" placeholder="PIS" required bind:value={entryPIS} />
        <br />
        <button type="submit">Search</button>
        <button type="reset" >Clear</button>
      </form>
    </Card>
{/if}
<Nav />

<style>
    p {
        margin-left: 10px;
        margin-right: 10px;
    }
    input {
        border: none;
        border-radius: 50px;
        font-family: urwgothic, sans-serif;
        text-align: center;
        text-transform: uppercase;
        width: 25%;
        max-width: 250px;
        height: 30px;
        font-size: 16px;
        margin-top: 10px;
        margin-bottom: 15px;
        margin-left: 10px;
        margin-right: 10px;
        box-shadow: var(--box-shadow);
    }
    button {
        border: none;
        border-radius: 50px;
        font-family: urwgothic, sans-serif;
        width: 25%;
        max-width: 175px;
        margin: 0px;
        margin-left: 10px;
        margin-right: 10px;
        margin-bottom: 15px;
        height: 30px;
        background-color: var(--island-button-color);
        color: white;
        font-size: 16px;
        box-shadow: var(--box-shadow);
    }
    table {
        width: 100%;
        margin: auto;
        color: white;
    }
    td {
        padding-top: 5px;
        padding-bottom: 5px;
    }
    .toc {
        width: 15%;
    }
    .code {
        width: 20%;
    }
    .toc-data {
        text-transform: uppercase;
    }
    .stops-data {
        text-align: left;
        font-family: firamono, monospace;
        text-transform: uppercase;
    }
    .error {
        color: white;
    }
    #reset {
        margin: 25px;
    }
</style>
