package net.viper.status;

import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * PlayerLoginLogger – schreibt bei jedem Join UUID, Name und IP
 * in die Datei plugins/StatusAPI/player-logins.log
 */
public class PlayerLoginLogger implements Listener {

    private static final DateTimeFormatter FMT =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

    private final Plugin plugin;
    private final File   logFile;
    private final ZoneId zoneId;

    public PlayerLoginLogger(Plugin plugin, ZoneId zoneId) {
        this.plugin  = plugin;
        this.zoneId  = zoneId;
        this.logFile = new File(plugin.getDataFolder(), "player-logins.log");

        // Sicherstellen, dass das Plugin-Verzeichnis existiert
        if (!plugin.getDataFolder().exists()) {
            plugin.getDataFolder().mkdirs();
        }
    }

    @EventHandler
    public void onPostLogin(PostLoginEvent event) {
        ProxiedPlayer player = event.getPlayer();

        String uuid = player.getUniqueId().toString();
        String name = player.getName();
        String ip   = "unknown";

        try {
            InetSocketAddress addr = (InetSocketAddress) player.getSocketAddress();
            if (addr != null && addr.getAddress() != null) {
                ip = addr.getAddress().getHostAddress();
            }
        } catch (Exception e) {
            plugin.getLogger().warning("[PlayerLoginLogger] Konnte IP nicht lesen: " + e.getMessage());
        }

        String timestamp = ZonedDateTime.now(zoneId).format(FMT);
        String line = String.format("[%s] UUID=%s | Name=%-16s | IP=%s",
                timestamp, uuid, name, ip);

        plugin.getLogger().info("[LoginLog] " + line);

        // In Datei schreiben (append)
        try (PrintWriter pw = new PrintWriter(new FileWriter(logFile, true))) {
            pw.println(line);
        } catch (IOException e) {
            plugin.getLogger().warning("[PlayerLoginLogger] Fehler beim Schreiben: " + e.getMessage());
        }
    }
}
