package de.viper.survivalplus.commands;

import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.configuration.file.FileConfiguration;

public class BackCommand implements CommandExecutor {
    private final SurvivalPlus plugin;

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

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(plugin.getLangConfig().getString("player-only", "§cDieser Befehl ist nur für Spieler!"));
            return true;
        }

        Player player = (Player) sender;
        FileConfiguration lang = plugin.getLangConfig();
        FileConfiguration gravesConfig = plugin.getGravesConfig();

        if (!player.hasPermission("survivalplus.back")) {
            player.sendMessage(lang.getString("no-permission", "§cDu hast keine Berechtigung für diesen Befehl!"));
            return true;
        }

        if (args.length != 0) {
            player.sendMessage(lang.getString("back.usage", "§cVerwendung: /back"));
            return true;
        }

        // Lade Todesposition
        String path = "graves." + player.getUniqueId();
        if (!gravesConfig.contains(path)) {
            player.sendMessage(lang.getString("back.no-death-point", "§cDu hast keinen Todespunkt!"));
            return true;
        }

        String worldName = gravesConfig.getString(path + ".world");
        double x = gravesConfig.getDouble(path + ".x");
        double y = gravesConfig.getDouble(path + ".y");
        double z = gravesConfig.getDouble(path + ".z");

        World world = plugin.getServer().getWorld(worldName);
        if (world == null) {
            player.sendMessage(lang.getString("back.no-death-point", "§cDu hast keinen Todespunkt!"));
            return true;
        }

        Location location = new Location(world, x, y, z);
        player.teleport(location);

        player.sendMessage(String.format(
            lang.getString("back.success", "§aTeleportiert zum Todespunkt bei x=%.2f, y=%.2f, z=%.2f!"),
            x, y, z
        ));
        return true;
    }
}
