package de.simolzimol.mclogger.paper.listeners;

import de.simolzimol.mclogger.paper.PaperLoggerPlugin;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Logs commands executed by players.
 * Chat is logged by the Velocity proxy with correct server context.
 *
 * @author SimolZimol
 */
public class PlayerChatCommandListener implements Listener {

    private final PaperLoggerPlugin plugin;

    public PlayerChatCommandListener(PaperLoggerPlugin plugin) {
        this.plugin = plugin;
    }

    /**
     * Command – logs with world/position, then notifies Velocity proxy.
     * Velocity will skip its own fallback log once it receives the plugin message.
     */
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onCommand(PlayerCommandPreprocessEvent event) {
        Player p = event.getPlayer();
        String cmd = event.getMessage(); // includes leading '/'
        plugin.getDb().insertCommand(
                p.getUniqueId().toString(),
                p.getName(),
                p.getWorld().getName(),
                cmd,
                p.getLocation().getX(),
                p.getLocation().getY(),
                p.getLocation().getZ()
        );
        // Notify Velocity proxy so it skips duplicate fallback logging
        String key = p.getUniqueId() + "|" + cmd;
        p.sendPluginMessage(plugin, "mclogger:logged", key.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * World change (e.g. Nether / End portal)
     */
    @EventHandler(priority = EventPriority.MONITOR)
    public void onWorldChange(PlayerChangedWorldEvent event) {
        Player p = event.getPlayer();
        Map<String, Object> details = new HashMap<>();
        details.put("from_world", event.getFrom().getName());
        details.put("to_world", p.getWorld().getName());
        plugin.getDb().insertPlayerStat(
                "world_change",
                p.getUniqueId().toString(),
                p.getName(),
                event.getFrom().getName(),
                p.getWorld().getName(),
                details
        );
    }
}
