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

import de.steamwar.core.Core;
import de.steamwar.network.packets.NetworkPacket;
import lombok.SneakyThrows;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import java.util.ArrayList;
import java.util.List;

public class NetworkSender implements Listener {

    private static List<NetworkPacket> queued = new ArrayList<>();

    static {
        Bukkit.getPluginManager().registerEvents(new NetworkSender(), Core.getInstance());
    }

    private NetworkSender() {
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        if (Bukkit.getOnlinePlayers().size() > 1) {
            return;
        }
        Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> {
            queued.forEach(NetworkSender::send);
            queued.clear();
        }, 1);
    }

    public static void sendOrQueue(NetworkPacket packet) {
        if (!Bukkit.getOnlinePlayers().isEmpty()) {
            send(packet);
        } else {
            queued.add(packet);
        }
    }

    public static void send(NetworkPacket packet) {
        Bukkit.getOnlinePlayers().stream().findAny().ifPresent(player -> send(packet, player));
    }

    @SneakyThrows
    public static void send(NetworkPacket packet, Player player) {
        player.sendPluginMessage(Core.getInstance(), "sw:bridge", packet.serialize());
    }
}
