/*
 *   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.tablist;

import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ServerConnection;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import de.steamwar.messages.Chatter;
import de.steamwar.persistent.Subserver;
import de.steamwar.velocitycore.VelocityCore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TablistBuild implements TablistPart {

    private final List<RegisteredServer> servers = new ArrayList<>();
    private final Map<RegisteredServer, List<Item>> players = new HashMap<>();

    public TablistBuild() {
        for (RegisteredServer server : VelocityCore.getProxy().getAllServers()) {
            if (server.getPlayersConnected().isEmpty() || !Subserver.isBuild(Subserver.getSubserver(server.getServerInfo()))) {
                continue;
            }

            servers.add(server);
            players.put(server, server.getPlayersConnected().stream().sorted(((p1, p2) -> p1.getUsername().compareToIgnoreCase(p2.getUsername()))).map(Item::new).toList());
        }
        servers.sort((s1, s2) -> s1.getServerInfo().getName().compareToIgnoreCase(s2.getServerInfo().getName()));
    }

    @Override
    public String sortKey() {
        return "Build";
    }

    @Override
    public void print(Chatter viewer, Player player, List<Item> tablist, List<Item> direct) {
        RegisteredServer server = player.getCurrentServer().map(ServerConnection::getServer).orElse(null);
        if (players.keySet().stream().anyMatch(info -> server != info)) {
            tablist.add(new Item(null, "", TablistServer.GRAY));
            tablist.add(new Item(null, viewer.parseToLegacy("TABLIST_BAU"), TablistServer.LIGHT_GRAY));
        }

        for (RegisteredServer info : servers) {
            TablistServer.teamify(players.get(info), player)
                    .forEach(((server == info) ? direct : tablist)::add);
        }
    }
}
