package de.viper.survivalplus.commands;

import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.ChatColor;
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;
import org.bukkit.inventory.meta.ItemMeta;

public class ItemRenameCommand implements CommandExecutor {

    private final SurvivalPlus plugin;

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

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player player)) {
            sender.sendMessage(ChatColor.RED + plugin.getMessage("ir.only-player"));
            return true;
        }

        if (!player.hasPermission("survivalplus.itemrename")) {
            player.sendMessage(ChatColor.RED + plugin.getMessage("ir.no-permission"));
            return true;
        }

        if (args.length == 0) {
            player.sendMessage(ChatColor.RED + plugin.getMessage("ir.no-name"));
            player.sendMessage(ChatColor.YELLOW + plugin.getMessage("ir.usage"));
            return true;
        }

        ItemStack item = player.getInventory().getItemInMainHand();
        if (item == null || item.getType().isAir()) {
            player.sendMessage(ChatColor.RED + plugin.getMessage("ir.no-item"));
            return true;
        }

        StringBuilder newNameBuilder = new StringBuilder();
        for (String arg : args) {
            newNameBuilder.append(arg).append(" ");
        }
        String newName = newNameBuilder.toString().trim();
        newName = ChatColor.translateAlternateColorCodes('&', newName);

        ItemMeta meta = item.getItemMeta();
        if (meta == null) {
            player.sendMessage(ChatColor.RED + plugin.getMessage("ir.cant-rename"));
            return true;
        }

        meta.setDisplayName(newName);
        item.setItemMeta(meta);

        player.sendMessage(ChatColor.GREEN + plugin.getMessage("ir.success").replace("{name}", newName));
        return true;
    }
}
