package de.viper.survivalplus.listeners;

import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class LoginListener implements Listener {

    private final SurvivalPlus plugin;

    public LoginListener(SurvivalPlus plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();

        if (!player.hasPlayedBefore()) {
            // Erster Login
            sendWelcomeMessage(player, true);
        } else {
            // Wiederkehrer
            sendWelcomeMessage(player, false);
        }
    }

    private void sendWelcomeMessage(Player player, boolean firstJoin) {
        String messageKey = firstJoin ? "welcome.first-join-message" : "welcome.return-message";
        String soundKey = firstJoin ? "welcome.first-join-sound" : "welcome.return-sound";
        String volumeKey = firstJoin ? "welcome.first-join-sound-volume" : "welcome.return-sound-volume";
        String pitchKey = firstJoin ? "welcome.first-join-sound-pitch" : "welcome.return-sound-pitch";

        String rawMessage = plugin.getLangConfig().getString(messageKey, "&6Willkommen, &e{player}&6!");
        String message = ChatColor.translateAlternateColorCodes('&', rawMessage.replace("{player}", player.getName()));
        player.sendMessage(message);

        String soundName = plugin.getLangConfig().getString(soundKey, "ENTITY_PLAYER_LEVELUP");
        float volume = (float) plugin.getLangConfig().getDouble(volumeKey, 1.0);
        float pitch = (float) plugin.getLangConfig().getDouble(pitchKey, 1.0);

        try {
            Sound sound = Sound.valueOf(soundName);
            player.playSound(player.getLocation(), sound, volume, pitch);
        } catch (IllegalArgumentException e) {
            plugin.getLogger().warning("Ungültiger Sound-Name in lang.yml: " + soundName);
        }
    }
}
