package pw.yumc.Residence.commandsub;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.bekvon.bukkit.residence.protection.ClaimedResidence;
import com.bekvon.bukkit.residence.protection.ResidenceManager;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;

import cn.citycraft.PluginHelper.commands.BaseCommand;
import pw.yumc.Residence.ResidenceMain;
import pw.yumc.Residence.selection.SelectionManager;
import pw.yumc.Residence.text.Language;

public class CommandSubZone extends BaseCommand {
    ResidenceMain plugin;

    public CommandSubZone(final ResidenceMain plugin) {
        super("subzone", "sz");
        this.plugin = plugin;
        setMinimumArguments(1);
        setOnlyPlayerExecutable();
        setPossibleArguments("<领地名> [附属领地名]");
    }

    @Override
    public void execute(final CommandSender sender, final Command command, final String label, final String[] args) throws CommandException {
        final Player player = (Player) sender;
        final boolean resadmin = (command != null);
        final ResidenceManager rmanager = plugin.getResidenceManager();
        final Language language = plugin.getLanguage();
        final SelectionManager smanager = plugin.getSelectionManager();
        if (args.length != 2 && args.length != 3) {
            return;
        }
        String zname;
        String parent;
        if (args.length == 1) {
            parent = rmanager.getNameByLoc(player.getLocation());
            zname = args[0];
        } else {
            parent = args[0];
            zname = args[1];
        }
        final WorldEditPlugin wep = (WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit");
        if (wep != null) {
            if (wep.getConfig().getInt("wand-item") == plugin.getConfigManager().getSelectionTooldID()) {
                smanager.worldEdit(player);
            }
        }
        if (smanager.hasPlacedBoth(player.getName())) {
            final ClaimedResidence res = rmanager.getByName(parent);
            if (res == null) {
                player.sendMessage(ChatColor.RED + language.getPhrase("InvalidResidence"));
                return;
            }
            res.addSubzone(player, smanager.getPlayerLoc1(player.getName()), smanager.getPlayerLoc2(player.getName()), zname, resadmin);
        } else {
            player.sendMessage(ChatColor.RED + language.getPhrase("SelectPoints"));
        }
    }

}
