/*
 *   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 com.velocitypowered.api.util.GameProfile;
import de.steamwar.messages.Chatter;
import de.steamwar.network.packets.common.FightInfoPacket;
import de.steamwar.persistent.Subserver;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.velocitycore.VelocityCore;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

public class TablistServer implements TablistPart {

    public static final List<GameProfile.Property> GRAY = List.of(new GameProfile.Property("textures", "eyJ0aW1lc3RhbXAiOjE0NTU1NzQxMTk0MzMsInByb2ZpbGVJZCI6ImIzYjE4MzQ1MzViZjRiNzU4ZTBjZGJmMGY4MjA2NTZlIiwicHJvZmlsZU5hbWUiOiIxMDExMTEiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzZlNzJkMzE0NzczMmQ5NzFkZWZhZTIzMWIzOGQ5NDI0MTRiMDU3YTcxNTFjNTNjNWZkNjI5NmEzYjllZGEwYWIifX19", "ro/ZKHt7278yhCr+CFTcPp/q6wAUlef//85k2DzkfRaZqy0CtGgwisDs2U4pVKvQ2pfXvitzWgbJvD0bLeQ12xWi4c1Fc29LCArosVJoFmrJDHz7N2MlstHT+ynQROb9d2aiFA6uOXfLjPKb1noUZ/YQoZjqcPIvD5oFZtD5DHV5O4hYz0IvgHbIjDqjz6ITsTcKiBlbxNg2loTFxSlW1ZfnNCO+kcAmeyB5NFY3j0e+/AqVANiNoiC3OKsECM/yEx/acf+vKWcT8mQn4wRoIGtxfEU7ZjNtgdh73NvXXBygW+K9AiJ242g8Y06Xxuk8kaNEGmT6H/mM7nbwjZmQQXpi/Pao2gYqyeIofeCPfr8RsGXoDX3nXDAw8/LyhTCHgx+sp6IQYSfGcSMJtoNeTJ0liIFxqn1V9/zKmzOZAPzR6qrQPOjoRFljLAlv7rfzotaEqh/1ldd40GdS8tstczn7f29OQerNDaqvbDb00Gy0STdUr1bVyCDptA54XKjT9WFv7QpBikEculxqSppAXPxD2Fb/ZmphbZx8WEGfG6bVFhf6fQdDAUXlcv8BxjElNPwlolF86M2KJd5VquLluhrCjwID7OK/pffNultAVH+Lxw4QOAXmJqjUrA1KHgyG1S0Cwj/f4E2hdxZJBvkfVtq9qPkd9nignhEoTCTOHf0="));
    public static final List<GameProfile.Property> LIGHT_GRAY = List.of(new GameProfile.Property("textures", "eyJ0aW1lc3RhbXAiOjE0NTU2MjU1OTM5NjIsInByb2ZpbGVJZCI6ImIzYjE4MzQ1MzViZjRiNzU4ZTBjZGJmMGY4MjA2NTZlIiwicHJvZmlsZU5hbWUiOiIxMDExMTEiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzc4Y2I3ZmMyMDhiMzM4NTUwNGE4MTQ0MjA0NDI4ZmRjZDYzMjRiZWIzMWNhMmNlODZjYzQyNGI5NjNkODVjIn19fQ==", "R/wZUZRC1dishRdM9a2SSxxW3oYa0XSb/MxHbQpEUA791HxyqjaKLDu0wFX2r2a8ZTeVjzXpNzkg3+PkrA11o8h7lt86MTD1pi/rQqj/WRuoqf2LP+ypbssKV+LU15cYez2cj3QQVcJDXgWEnfSLNuBv6NG8BDUpUAjTWldvu99NCJHUoD0jNMHxY/fu4k5vCgOjaBaKgkjVk2bmUhegusmtMwco+3pYx+y8+gUW8ptx5SnePG+dOwTqLyBFiOt2AQ+gSvbU/jP9aAXgxOwz/b1pMaBWtzVhFU865NHlIdSpIHg/sh3uNah3a7gTgtTvxPQv1OzM/KtqYKiamsrRzAQMzRcs4A7Tp0GakLuxEaz401IwvQ7UGVYLFzGUVLB2MyqtPgifiqQSQxZpiqj9sM5QadhsUw00nfX7mTdW46U0MtNIbby1rLrvgQKoj08zt6LJlhI3yjyawy4iZkgF4oc+PCNwZc93GIbVL9LJaGkXk3RVA+JpGwfMJrGVbL7hl8ibbAcUv7uCEWdkAgZCd6w75jEE4tlhDSPDD4rXbn+FeTZRg2n/PGKtnoTZRzbniiFaNoSAHDZSVRG39xvBDFvtmL3SPaKhzKaifiYrgNn453WtR3kymqdAtPf1GN9d1VltGZ/+vMPwqPJb6thcrlcU64UGHbg1olRkiyZHvY8="));

    private final RegisteredServer server;
    private final List<Item> players;

    public TablistServer(RegisteredServer server) {
        this(server, server.getPlayersConnected().stream().sorted((p1, p2) -> p1.getUsername().compareToIgnoreCase(p2.getUsername())).map(TablistPart.Item::new).toList());
    }

    public TablistServer(RegisteredServer server, FightInfoPacket info) {
        this(server, new ArrayList<>());

        Collection<Player> onlinePlayers = server.getPlayersConnected();
        addPlayers(info.getBlueName().substring(0, 2), info.getBluePlayers(), onlinePlayers);
        addPlayers(info.getRedName().substring(0, 2), info.getRedPlayers(), onlinePlayers);
        addPlayers("§7", info.getSpectators(), onlinePlayers);
    }

    public TablistServer(RegisteredServer server, List<Item> players) {
        this.server = server;
        this.players = players;
    }

    @Override
    public String sortKey() {
        return server.getServerInfo().getName();
    }

    @Override
    public void print(Chatter viewer, Player player, List<Item> tablist, List<Item> direct) {
        boolean onServer = player.getCurrentServer().map(ServerConnection::getServer).orElse(null) == server;
        List<Item> items = onServer ? direct : tablist;

        if (!onServer) {
            items.add(new Item(null, "", GRAY));
            items.add(new Item(null, "§7§l" + server.getServerInfo().getName(), LIGHT_GRAY));
        }

        teamify(players, player).forEach(items::add);
    }

    private void addPlayers(String prefix, List<Integer> teamPlayers, Collection<Player> onlinePlayers) {
        teamPlayers.stream().map(SteamwarUser::byId).map(
                user -> onlinePlayers.stream().filter(player -> player.getUniqueId().equals(user.getUUID())).findAny()
        ).filter(Optional::isPresent).map(Optional::get).sorted(
                (p1, p2) -> p1.getUsername().compareToIgnoreCase(p2.getUsername())
        ).forEachOrdered(player -> players.add(new Item(player.getUniqueId(), prefix + player.getUsername(), player.getGameProfileProperties())));
    }

    public static Stream<Item> teamify(List<Item> players, Player player) {
        int team = SteamwarUser.get(player.getUniqueId()).getTeam();
        if (team == 0) return players.stream();
        return players.stream().map(item -> {
            Player p = VelocityCore.getProxy().getPlayer(item.getUuid()).orElse(null);
            if (p == null) return item;
            if (Subserver.isArena(Subserver.getSubserver(p.getCurrentServer().map(ServerConnection::getServerInfo).orElse(null)))) {
                return item;
            }
            if (SteamwarUser.get(p.getUniqueId()).getTeam() != team) return item;
            return new Item(p, true);
        });
    }
}
