package de.viper.survivalplus.commands;

import de.viper.survivalplus.Manager.Warp;
import de.viper.survivalplus.Manager.WarpManager;
import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

public class SetWarpCommand implements CommandExecutor {

    private final SurvivalPlus plugin;
    private final WarpManager warpManager;

    public SetWarpCommand(SurvivalPlus plugin, WarpManager warpManager) {
        this.plugin = plugin;
        this.warpManager = warpManager;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(plugin.getMessage("warp.only_players"));
            return true;
        }
        Player player = (Player) sender;

        if (args.length < 1) {
            player.sendMessage(ChatColor.RED + "Benutze: /setwarp <name>");
            return true;
        }

        String warpName = args[0];

        int maxWarps = plugin.getConfig().getInt("maxWarpsPerPlayer", 5);
        int currentWarpCount = warpManager.getWarpCountForPlayer(player.getName());

        Warp existingWarp = warpManager.getWarp(player.getName(), warpName);

        // Limit prüfen - Falls Warp mit dem Namen schon existiert, Update erlaubt
        if (currentWarpCount >= maxWarps && existingWarp == null) {
            player.sendMessage(ChatColor.RED + "Du hast das maximale Warp-Limit von " + maxWarps + " erreicht.");
            return true;
        }

        ItemStack item = player.getInventory().getItemInMainHand();

        // Default Item wenn leer (aus config oder Schild)
        if (item == null || item.getType().isAir()) {
            String defaultItemName = plugin.getConfig().getString("defaultWarpItem", "OAK_SIGN");
            try {
                item = new org.bukkit.inventory.ItemStack(org.bukkit.Material.valueOf(defaultItemName));
            } catch (IllegalArgumentException e) {
                item = new org.bukkit.inventory.ItemStack(org.bukkit.Material.OAK_SIGN);
            }
        }

        Location loc = player.getLocation();
        Warp warp = new Warp(player.getName(), warpName, item, loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ());
        warpManager.addWarp(warp);
        player.sendMessage(plugin.getMessage("warp.set_success").replace("%warp%", warpName));
        return true;
    }
}
