package de.teleportsuite.bungee.listener;

import de.teleportsuite.bungee.TeleportSuiteBungee;
import de.teleportsuite.bungee.manager.PendingTpa;
import de.teleportsuite.bungee.manager.TeleportMessageListener;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;

import java.io.*;

/**
 * Cleans up pending TPA requests when a player disconnects.
 */
public class PlayerConnectionListener implements Listener {

    private final TeleportSuiteBungee plugin;

    public PlayerConnectionListener(TeleportSuiteBungee plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onDisconnect(PlayerDisconnectEvent event) {
        String name = event.getPlayer().getName();

        // Player was a requester
        PendingTpa tpa = TeleportMessageListener.getPendingTpa().remove(name);
        if (tpa != null) {
            notifyOther(tpa.getToName(), name);
            return;
        }

        // Player was a target — find the requester
        TeleportMessageListener.getPendingTpa().entrySet().removeIf(entry -> {
            if (entry.getValue().getToName().equalsIgnoreCase(name)) {
                notifyOther(entry.getValue().getFromName(), name);
                return true;
            }
            return false;
        });
    }

    private void notifyOther(String otherName, String disconnectedName) {
        ProxiedPlayer other = plugin.getProxy().getPlayer(otherName);
        if (other == null || other.getServer() == null) return;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             DataOutputStream out = new DataOutputStream(bos)) {
            out.writeUTF("SEND_MSG");
            out.writeUTF(otherName);
            out.writeUTF("§cDeine TPA-Anfrage wurde abgebrochen, da §6" + disconnectedName + " §cdas Netzwerk verlassen hat.");
            other.getServer().sendData(TeleportSuiteBungee.CHANNEL_TO_SPIGOT, bos.toByteArray());
        } catch (IOException e) {
            plugin.getLogger().warning("Disconnect-Benachrichtigung fehlgeschlagen: " + e.getMessage());
        }
    }
}
