/*
 *   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 {FightStats, Ranking, UserStats} from "@type/stats.ts";
import {fetchWithToken, tokenStore} from "./repo.ts";
import {FightStatsSchema, RankingSchema, UserStatsSchema} from "@type/stats.ts";
import {derived} from "svelte/store";

export class StatsRepo {

    constructor(private token: string) {
    }

    public async getRankings(gamemode: string): Promise<Ranking> {
        return await fetchWithToken(this.token, `/stats/ranked/${gamemode}`).then(value => value.json()).then(RankingSchema.parse);
    }

    public async getFightStats(): Promise<FightStats> {
        return await fetchWithToken(this.token, "/stats/fights").then(value => value.json()).then(FightStatsSchema.parse);
    }

    public async getUserStats(id: number): Promise<UserStats> {
        return await fetchWithToken(this.token, `/stats/user/${id}`).then(value => value.json()).then(UserStatsSchema.parse);
    }
}

export const statsRepo = derived(tokenStore, ($token) => new StatsRepo($token));