/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 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/>.
 */

package de.steamwar.velocitycore.network.handlers;

import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import de.steamwar.linkage.Linked;
import de.steamwar.network.packets.PacketHandler;
import de.steamwar.network.packets.common.FightInfoPacket;
import de.steamwar.velocitycore.network.NetworkSender;
import de.steamwar.velocitycore.network.ServerMetaInfo;
import de.steamwar.velocitycore.tablist.TablistManager;

import java.util.HashSet;
import java.util.Set;

@Linked
public class FightInfoHandler extends PacketHandler {

    private static final Set<RegisteredServer> lobbys = new HashSet<>();

    public static void addLobby(RegisteredServer lobby) {
        lobbys.add(lobby);
    }

    public static boolean onLobby(Player player) {
        return player.getCurrentServer().map(connection -> lobbys.contains(connection.getServer())).orElse(false);
    }

    @Handler
    public void handle(FightInfoPacket packet) {
        RegisteredServer server = ((ServerMetaInfo) packet.getMetaInfos()).sender().getServer();

        FightInfoPacket lobbyPacket = packet.withServerName(server.getServerInfo().getName());

        TablistManager.newFightInfo(server, packet);

        lobbys.removeIf(s -> s.getPlayersConnected().isEmpty());
        lobbys.forEach(lobby -> NetworkSender.send(lobby, lobbyPacket));
    }
}
