import { writable, type Writable } from "svelte/store";
import { browser } from "$app/environment";
import type { NearestStationResponse } from "@owlboard/ts-types";

export const nearToMeCache = writable(fromSessionStorage("nearToMeCache", []));
toSessionStorage(nearToMeCache, "nearToMeCache");

function fromSessionStorage(storageKey: string, fallback: NearestStationResponse[]): NearestStationResponse[] {
    if (browser) {
        const storedValue = sessionStorage.getItem(storageKey);
        if (storedValue !== "undefined" && storedValue !== null) {
            return typeof fallback === "object" ? JSON.parse(storedValue) : storedValue;
        }
    }
    return fallback;
}

function toSessionStorage(store: Writable<NearestStationResponse[]>, storageKey: string) {
    if (browser) {
        store.subscribe((value) => {
            let storageValue = typeof value === "object" ? JSON.stringify(value.sort()) : value;

            sessionStorage.setItem(storageKey, storageValue);
        });
    }
}
