/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2023 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

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

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));
