package de.viper.survivalplus.commands;

import de.viper.survivalplus.Manager.BlockManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;

public class UnblockCommand implements CommandExecutor {

    private final BlockManager blockManager;
    private final FileConfiguration config;

    public UnblockCommand(BlockManager blockManager, FileConfiguration config) {
        this.blockManager = blockManager;
        this.config = config;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

        if (!(sender instanceof Player player)) {
            sender.sendMessage(color(config.getString("messages.general.only_players", "§cDieser Befehl ist nur für Spieler!")));
            return true;
        }

        if (!player.hasPermission("survivalplus.unblock")) {
            player.sendMessage(color(config.getString("messages.general.no_permission", "§cDu hast keine Berechtigung für diesen Befehl!")));
            return true;
        }

        if (args.length != 1) {
            player.sendMessage(color(config.getString("messages.block.usage", "§cVerwendung: /unblock <Spieler>")));
            return true;
        }

        Player target = Bukkit.getPlayerExact(args[0]);
        if (target == null || target == player) {
            player.sendMessage(color(config.getString("messages.block.invalid_player", "§cDieser Spieler konnte nicht gefunden werden oder bist du selbst.")));
            return true;
        }

        if (!blockManager.hasBlocked(player, target)) {
            String msg = config.getString("messages.block.not_blocked", "&cDieser Spieler ist nicht blockiert.");
            player.sendMessage(color(msg.replace("%player%", target.getName())));
        } else {
            blockManager.unblockPlayer(player, target);
            String msg = config.getString("messages.block.unblocked", "&aDu hast %player% entblockt.");
            player.sendMessage(color(msg.replace("%player%", target.getName())));
        }

        return true;
    }
    
    private String color(String msg) {
        if (msg == null) return "";
        return ChatColor.translateAlternateColorCodes('&', msg);
    }
}