/*
 *   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, Server} from "@type/data.ts";
import {PlayerSchema, ServerSchema} from "@type/data.ts";
import {fetchWithToken, tokenStore} from "./repo.ts";
import {derived} from "svelte/store";

export class DataRepo {
    constructor(private token: string) {
    }

    public async getServer(): Promise<Server> {
        return await fetchWithToken(this.token, "/data/server").then(value => value.json()).then(ServerSchema.parse);
    }

    public async getMe(): Promise<Player> {
        return await fetchWithToken(this.token, "/data/me").then(value => value.json()).then(PlayerSchema.parse);
    }
}

export const dataRepo = derived(tokenStore, ($token) => new DataRepo($token));