package de.viper.survivalplus.listeners;

import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBedLeaveEvent;

public class SleepListener implements Listener {

    private final SurvivalPlus plugin;
    private double requiredPercentage;

    public SleepListener(SurvivalPlus plugin) {
        this.plugin = plugin;
        reloadConfig(plugin.getConfig());
    }

    public void reloadConfig(FileConfiguration config) {
        this.requiredPercentage = config.getDouble("sleep.required-percentage", 50.0);
    }

    @EventHandler
    public void onPlayerBedEnter(PlayerBedEnterEvent event) {
        Bukkit.getScheduler().runTaskLater(plugin, () -> checkSleepProgress(event.getPlayer().getWorld()), 1L);
    }

    @EventHandler
    public void onPlayerBedLeave(PlayerBedLeaveEvent event) {
        Bukkit.getScheduler().runTaskLater(plugin, () -> checkSleepProgress(event.getPlayer().getWorld()), 1L);
    }

    private void checkSleepProgress(World world) {
        long time = world.getTime();
        if (time < 12541 || time > 23458) return; // Nur bei Nacht prüfen

        int sleeping = 0;
        int total = 0;

        for (Player player : world.getPlayers()) {
            if (player.isSleepingIgnored()) continue;
            total++;
            if (player.isSleeping()) sleeping++;
        }

        if (total == 0) return;

        double percent = (sleeping * 100.0) / total;

        if (percent >= requiredPercentage) {
            world.setTime(0);
            world.setStorm(false);
            world.setThundering(false);
            Bukkit.broadcastMessage(plugin.getMessage("sleep.skipped")
                .replace("%sleeping%", String.valueOf(sleeping))
                .replace("%total%", String.valueOf(total)));
        } else {
            Bukkit.broadcastMessage(plugin.getMessage("sleep.progress")
                .replace("%sleeping%", String.valueOf(sleeping))
                .replace("%total%", String.valueOf(total))
                .replace("%required%", String.valueOf(requiredPercentage)));
        }
    }
}