package eu.mhsl.craftattack.teamLobby;

import com.google.common.reflect.TypeToken;
import eu.mhsl.craftattack.teamLobby.data.Team;
import eu.mhsl.craftattack.teamLobby.http.Request;
import net.minestom.server.entity.Player;
import org.jetbrains.annotations.NotNull;

import java.net.http.HttpRequest;
import java.util.*;

public class LobbyManager {
    public LobbyManager() {
        this.loadTeams();
    }

    private Set<Team> teams = Set.of();
    private final Map<Team, Lobby> instances = new HashMap<>();

    private void loadTeams() {
        HttpRequest request = Request.builder(Request.uri("team"))
            .GET()
            .build();

        this.teams = Request.execute(request, new TypeToken<Set<Team>>(){}.getType()).cast();
    }

    public synchronized @NotNull Lobby getPlayerInstance(Player player) {
        UUID playerId = player.getUuid();
        Team targetTeam = this.teams.stream()
            .filter(team -> team.users().stream().anyMatch(user -> user.uuid().equals(playerId)))
            .findAny()
            .orElseThrow(() -> new NoSuchElementException("Dein Account konnte nicht zugeordnet werden. Falls dies ein Fehler ist kontaktiere bitte einen Admin."));

        if(!this.instances.containsKey(targetTeam)) {
            Lobby instance = new Lobby(targetTeam);
            this.instances.put(targetTeam, instance);
        }

        return this.instances.get(targetTeam);
    }
}
