package de.viper.survivalplus.listeners;

import de.viper.survivalplus.Manager.StatsManager;
import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class StatsListener implements Listener {

    private final SurvivalPlus plugin;
    private final StatsManager statsManager;

    // Spielzeit-Tracking
    private final Map<UUID, Long> joinTimes = new HashMap<>();

    public StatsListener(SurvivalPlus plugin, StatsManager statsManager) {
        this.plugin = plugin;
        this.statsManager = statsManager;
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        joinTimes.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        UUID uuid = event.getPlayer().getUniqueId();
        long joinTime = joinTimes.getOrDefault(uuid, System.currentTimeMillis());
        long now = System.currentTimeMillis();
        long secondsPlayed = (now - joinTime) / 1000;

        statsManager.addPlayTime(uuid, secondsPlayed);
        statsManager.saveStats();

        joinTimes.remove(uuid);
    }

    @EventHandler
    public void onPlayerDeath(PlayerDeathEvent event) {
        Player player = event.getEntity();
        UUID uuid = player.getUniqueId();
        statsManager.addDeaths(uuid, 1);
        statsManager.saveStats();

        // Optional: Kill-Stat beim Killer erhöhen
        if (player.getKiller() != null) {
            Player killer = player.getKiller();
            statsManager.addKills(killer.getUniqueId(), 1);
            statsManager.saveStats();
        }
    }

    @EventHandler
    public void onBlockBreak(BlockBreakEvent event) {
        Player player = event.getPlayer();
        UUID uuid = player.getUniqueId();
        statsManager.addBlocksBroken(uuid, 1);
        statsManager.saveStats();
    }

    @EventHandler
    public void onBlockPlace(BlockPlaceEvent event) {
        Player player = event.getPlayer();
        UUID uuid = player.getUniqueId();
        statsManager.addBlocksPlaced(uuid, 1);
        statsManager.saveStats();
    }
}
