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

import de.steamwar.network.NetworkSender;
import de.steamwar.network.packets.common.FightInfoPacket;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.towerrun.config.Config;
import de.steamwar.towerrun.game.TowerRunGame;
import de.steamwar.towerrun.state.GameState;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;

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

public class FightInfoPacketSender implements Runnable {

    private final World world = Bukkit.getWorlds().get(0);

    private final String serverName = Bukkit.getServer().getName();
    private final String gameMode = "towerrun";
    private final String worldName = world.getName();
    private final String blueName = "§3Escaped";
    private final String redName = "§cAlive";

    @Override
    public void run() {
        if (Config.test()) {
            return;
        }

        List<Integer> alivePlayers = TowerRunGame.PLAYERS_ALIVE.stream().map(player -> SteamwarUser.get(player.player().getUniqueId()).getId()).collect(Collectors.toList());
        List<Integer> escapedPlayers = TowerRunGame.PLAYERS_ESCAPED.stream().map(player -> SteamwarUser.get(player.player().getUniqueId()).getId()).collect(Collectors.toList());
        List<Integer> spectatorPlayers = new ArrayList<>();
        for (Player player : Bukkit.getOnlinePlayers()) {
            int id = SteamwarUser.get(player.getUniqueId()).getId();
            if (!alivePlayers.contains(id) && !escapedPlayers.contains(id)) {
                spectatorPlayers.add(id);
            }
        }

        NetworkSender.send(new FightInfoPacket(serverName, gameMode, worldName, blueName, redName, GameState.getCurrentState().name().toLowerCase(), TowerRun.getGameCountdown().getPlayTimeInSeconds(), 0, 0, 0, 0, escapedPlayers, alivePlayers, spectatorPlayers));
    }
}
