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

import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ServerConnection;
import de.steamwar.command.SWCommand;
import de.steamwar.linkage.Linked;
import de.steamwar.messages.Chatter;
import de.steamwar.persistent.Subserver;
import de.steamwar.velocitycore.VelocityCore;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;

@Linked
public class ListCommand extends SWCommand {

    public ListCommand() {
        super("list");
    }

    public static synchronized SortedMap<String, List<Player>> getCustomTablist() {
        SortedMap<String, List<Player>> playerMap = new TreeMap<>();
        for (Player player : VelocityCore.getProxy().getAllPlayers()) {
            ServerConnection pserver = player.getCurrentServer().orElse(null);
            if (pserver == null) continue;

            if (Subserver.isBuild(Subserver.getSubserver(pserver.getServerInfo()))) {
                playerMap.computeIfAbsent("Bau", s -> new ArrayList<>()).add(player);
            } else {
                playerMap.computeIfAbsent(pserver.getServerInfo().getName(), s -> new ArrayList<>()).add(player);
            }
        }
        playerMap.forEach((server, players) -> players.sort((player, t1) -> player.getUsername().compareToIgnoreCase(t1.getUsername())));
        return playerMap;
    }

    @Register
    public void list(Chatter sender) {
        SortedMap<String, List<Player>> playerMap = getCustomTablist();
        for (String server : playerMap.keySet()) {
            String serverName = server;
            if (server.equals("Bau")) {
                serverName = sender.parseToLegacy("TABLIST_BAU");
            }
            sender.prefixless("LIST_COMMAND", serverName, playerMap.get(server).size(), playerMap.get(server).stream().map(Player::getUsername).collect(Collectors.joining(", ")));
        }
    }
}
