import type {Player, SchematicType} from "../types/data.js";
import {PlayerSchema} from "../types/data.js";
import {cached, cachedFamily} from "./cached.js";
import type {Team} from "../types/team.js";
import {TeamSchema} from "../types/team.js";
import {derived, get, writable} from "svelte/store";
import {dataRepo, fetchWithToken, pageRepo, tokenStore} from "../repo/repo.js";
import {z} from "zod";

export const schemTypes = cached<SchematicType[]>([], () =>
    fetchWithToken(get(tokenStore), `/data/schematicTypes`)
        .then(res => res.json()))

export const players = cached<Player[]>([], async () => {
    const res = await fetchWithToken(get(tokenStore), `/data/users`);
    return z.array(PlayerSchema).parse(await res.json());
})

export const gamemodes = cached<string[]>([], async () => {
    const res = await fetchWithToken(get(tokenStore), `/data/gamemodes`);
    return z.array(z.string()).parse(await res.json());
})

export const maps = cachedFamily<string, string[]>([], async (gamemode) => {
    if (get(gamemodes).every(value => value !== gamemode)) return [];

    const res = await fetchWithToken(get(tokenStore), `/data/gamemodes/${gamemode}/maps`);
    if (!res.ok) {
        return [];
    } else {
        return res.json();
    }
})

export const groups = cached<string[]>([], async () => {
    const res = await fetchWithToken(get(tokenStore), `/data/groups`);
    return z.array(z.string()).parse(await res.json());
})

export const teams = cached<Team[]>([], async () => {
    const res = await fetchWithToken(get(tokenStore), `/team`);
    return z.array(TeamSchema).parse(await res.json());
})

export const branches = cached<string[]>([], async () => {
    const res = await get(pageRepo).getBranches();
    return z.array(z.string()).parse(res);
})

export const server = derived(dataRepo, $dataRepo => $dataRepo.getServer());

export const isWide = writable(window.innerWidth >= 640);
window.addEventListener("resize", () => isWide.set(window.innerWidth >= 640));
