<script lang="ts">
    import Island from "$lib/islands/island.svelte";
    import Header from "$lib/navigation/header.svelte";
    import Loading from "$lib/navigation/loading.svelte";
    import Nav from "$lib/navigation/nav.svelte";
    import { getApiUrl } from "$lib/scripts/upstream";
    import { featureDetect, type FeatureDetectionResult } from "$lib/scripts/featureDetect";
    import { getCurrentLocation } from "$lib/scripts/getLocation";
    import { onMount } from "svelte";
    const title = "Statistics";
    let features: FeatureDetectionResult | null = null;
    let error: Error | null = null;

    async function getData() {
        const url = `${getApiUrl()}/misc/server/stats`;
        const res = await fetch(url);
        return await res.json();
    }

    async function loadFeatures() {
        try {
            features = await featureDetect();
        } catch (e) {
            error = e;
        }
    }

    onMount(() => {
        loadFeatures();
    });

    function U2L(input: Date | number): string {
        if (input instanceof Date) {
            return input.toLocaleString();
        }
        try {
            const datetime = new Date(input * 1000);
            return datetime.toLocaleString();
        } catch (err) {
            console.log(err);
            return "Unknown";
        }
    }
</script>

<Header {title} />

{#await getData()}
    <Loading />
{:then data}
    <br />
    <p>API Server:<br /><span>{data?.hostname}</span></p>
    <p>Runtime Mode: <span>{data?.runtimeMode}</span></p>
    <p>Stats Reset: <span>{U2L(data?.reset) || "Unknown"}</span></p>
    <h2>Last Update</h2>
    <p>Timetable: <span>{U2L(data?.updateTimes?.timetable)}</span></p>
    <p>Location Ref: <span>{U2L(data?.updateTimes?.corpus)}</span></p>
    <p>PIS Codes: <span>{U2L(data?.updateTimes?.pis)}</span></p>
    <p>Reason Codes: <span>{U2L(data?.updateTimes?.reasonCodes)}</span></p>

    <h2>Request Counts</h2>
    <p>LDBWS API: <span>{data?.requestCounts?.ldbws_api}</span></p>
    <p>LDBSVWS API: <span>{data?.requestCounts?.lsbsvws_api}</span></p>
    <p>Location Reference API: <span>{data?.requestCounts?.corpus_api}</span></p>
    <p>Timetable: <span>{data?.requestCounts?.timetable_db}</span></p>
    <p>PIS: <span>{data?.requestCounts?.pis_db}</span></p>
    <p>Location Reference: <span>{data?.requestCounts?.corpus_db}</span></p>
    <p>Stations: <span>{data?.requestCounts?.stations_db}</span></p>

    <h2>Database Lengths</h2>
    <p>Users: <span>{data?.dbLengths?.users}</span></p>
    <p>Pending Registrations: <span>{data?.dbLengths?.registrations}</span></p>
    <p>CORPUS: <span>{data?.dbLengths?.corpus}</span></p>
    <p>Stations: <span>{data?.dbLengths?.stations}</span></p>
    <p>PIS: <span>{data?.dbLengths?.pis}</span></p>
    <p>Timetable: <span>{data?.dbLengths?.timetable}</span></p>
    <p>Reason Codes: <span>{data?.dbLengths?.reasonCodes}</span></p>
{:catch}
    <Island>
        <p style="font-weight:600">Unable to connect to server</p>
    </Island>
{/await}

<h2>Browser Features</h2>
{#if features === null && error === null}
    Checking browser features...
{:else if features !== null}
    <h3>Critical Features</h3>
    {#if !features.critical}
        <p>
            OwlBoard will not function properly without these browser features. If you see any crosses here you may need to update your browser or choose another browser. Chrome,
            Edge, Firefox, Brave & Samsung Browser have been tested.
        </p>
    {/if}
    <ul class="feature-list">
        <li>
            Fetch <span class="feature-status {features.missing.includes('fetch') ? 'cross' : 'tick'}">
                {features.missing.includes("fetch") ? "✗" : "✓"}
            </span>
        </li>
        <li>
            Local Storage <span class="feature-status {features.missing.includes('localStorage') ? 'cross' : 'tick'}">
                {features.missing.includes("localStorage") ? "✗" : "✓"}
            </span>
        </li>
        <li>
            Session Storage <span class="feature-status {features.missing.includes('sessionStorage') ? 'cross' : 'tick'}">
                {features.missing.includes("sessionStorage") ? "✗" : "✓"}
            </span>
        </li>
        <li>
            Promises <span class="feature-status {features.missing.includes('promise') ? 'cross' : 'tick'}">
                {features.missing.includes("promise") ? "✗" : "✓"}
            </span>
        </li>
    </ul>

    <h3>Nice-to-have Features</h3>
    {#if !features.nice}
        <p>
            OwlBoard may run slowly or be missing some functions without these browser features. If you see any crosses here you may want to update your browser or choose another
            browser for improved performance. Chrome, Edge, Firefox, Brave & Samsung Browser have been tested.
        </p>
    {/if}
    <ul class="feature-list">
        <li>
            Geolocation <span class="feature-status {features.missing.includes('geolocation') ? 'cross' : 'tick'}">
                {features.missing.includes("geolocation") ? "✗" : "✓"}
            </span>
        </li>
        <li>
            Service Worker <span class="feature-status {features.missing.includes('serviceWorker') ? 'cross' : 'tick'}">
                {features.missing.includes("serviceWorker") ? "✗" : "✓"}
            </span>
        </li>
        <li>
            Dialog <span class="feature-status {features.missing.includes('dialog') ? 'cross' : 'tick'}">
                {features.missing.includes("dialog") ? "✗" : "✓"}
            </span>
        </li>
        <li>
            Popover API <span class="feature-status {features.missing.includes('popover') ? 'cross' : 'tick'}">
                {features.missing.includes("popover") ? "✗" : "✓"}
            </span>
        </li>
    </ul>
{:else if error !== null}
    Failed to detect browser features: {error.message}
{/if}

<Nav />

<style>
    span {
        color: white;
    }
    p {
        margin: 0;
        color: lightgray;
    }
    h2 {
        font-family: urwgothic, sans-serif;
        margin-bottom: 2px;
        margin-top: 8px;
    }
    .feature-list {
        list-style-type: none; /* Remove bullet points */
        padding: 0;
        text-align: center; /* Center the list */
    }

    .feature-list li {
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 8px 0;
    }

    .feature-status {
        display: inline-block;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        border-radius: 50%;
        color: white;
        margin-left: 8px;
    }

    .tick {
        background-color: green;
    }

    .cross {
        background-color: red;
    }
</style>
