Search in sources :

Example 1 with PlotPreChangeTypeEvent

use of com.palmergames.bukkit.towny.event.PlotPreChangeTypeEvent in project Towny by TownyAdvanced.

the class PlotCommand method parsePlotCommand.

public boolean parsePlotCommand(Player player, String[] split) {
    TownyPermissionSource permSource = TownyUniverse.getInstance().getPermissionSource();
    if (split.length == 0 || split[0].equalsIgnoreCase("?")) {
        HelpMenu.PLOT_HELP.send(player);
    } else {
        Resident resident = TownyUniverse.getInstance().getResident(player.getUniqueId());
        if (resident == null) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_not_registered"));
            return true;
        }
        String world = player.getWorld().getName();
        try {
            TownBlock townBlock = TownyAPI.getInstance().getTownBlock(player);
            if (townBlock == null && !split[0].equalsIgnoreCase("perm") && !split[0].equalsIgnoreCase("claim"))
                throw new TownyException(Translatable.of("msg_not_claimed_1"));
            if (!TownyAPI.getInstance().isWilderness(player.getLocation()) && townBlock.getTownOrNull().isRuined())
                throw new TownyException(Translatable.of("msg_err_cannot_use_command_because_town_ruined"));
            if (split[0].equalsIgnoreCase("claim")) {
                if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_CLAIM.getNode()))
                    throw new TownyException(Translatable.of("msg_err_command_disable"));
                List<WorldCoord> selection = AreaSelectionUtil.selectWorldCoordArea(resident, new WorldCoord(world, Coord.parseCoord(player)), StringMgmt.remFirstArg(split), true);
                // Fast-fail if this is a single plot and it is already claimed.
                if (selection.size() == 1 && selection.get(0).hasTownBlock() && selection.get(0).getTownBlock().hasResident() && !selection.get(0).getTownBlock().isForSale())
                    throw new TownyException(Translatable.of("msg_already_claimed", selection.get(0).getTownBlock().getResidentOrNull()));
                // Filter to just plots that are for sale.
                selection = AreaSelectionUtil.filterPlotsForSale(selection);
                // Filter out plots already owned by the player.
                selection = AreaSelectionUtil.filterUnownedBlocks(resident, selection);
                if (selection.size() > 0) {
                    if (selection.size() + resident.getTownBlocks().size() > TownySettings.getMaxResidentPlots(resident))
                        throw new TownyException(Translatable.of("msg_max_plot_own", TownySettings.getMaxResidentPlots(resident)));
                    /*
						 * If a resident has no town, the Town is open, and the plot is not an Embassy:
						 * Attempt to add the Resident to the town IF the town is not null, the Town is
						 * not going to exceed the maxResidentsWithoutANation value, and the Town will 
						 * not exceed the maxResidentsPerTown value.
						 */
                    if (!resident.hasTown() && townBlock.getTownOrNull().isOpen() && !townBlock.getType().equals(TownBlockType.EMBASSY)) {
                        final Town town = townBlock.getTownOrNull();
                        if (town == null || (TownySettings.getMaxNumResidentsWithoutNation() > 0 && !town.hasNation() && town.getResidents().size() >= TownySettings.getMaxNumResidentsWithoutNation()) || (TownySettings.getMaxResidentsPerTown() > 0 && town.getResidents().size() >= TownySettings.getMaxResidentsForTown(town)) || town.hasOutlaw(resident) || (resident.isOnline() && !resident.getPlayer().hasPermission(PermissionNodes.TOWNY_COMMAND_TOWN_JOIN.getNode()))) {
                        // Town is null (unlikely) or it would have too many residents, we won't be adding
                        // them to the town, continue as per usual (it could be an embassy plot.)
                        } else {
                            final List<WorldCoord> coords = selection;
                            Confirmation.runOnAccept(() -> {
                                try {
                                    resident.setTown(town);
                                } catch (AlreadyRegisteredException ignored) {
                                }
                                try {
                                    continuePlotClaimProcess(coords, resident, player);
                                } catch (TownyException e) {
                                    TownyMessaging.sendErrorMsg(player, e.getMessage(player));
                                }
                            }).setTitle(Translatable.of("msg_you_must_join_this_town_to_claim_this_plot", town.getName())).sendTo(player);
                            return true;
                        }
                    }
                    continuePlotClaimProcess(selection, resident, player);
                } else {
                    TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_empty_area_selection"));
                }
            } else if (split[0].equalsIgnoreCase("evict")) {
                if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_EVICT.getNode()))
                    throw new TownyException(Translatable.of("msg_err_command_disable"));
                if (!townBlock.hasResident()) {
                    TownyMessaging.sendErrorMsg(player, Translatable.of("msg_no_one_to_evict"));
                } else {
                    // Test we are allowed to work on this plot
                    // If this fails it will trigger a TownyException.
                    plotTestOwner(resident, townBlock);
                    if (townBlock.hasPlotObjectGroup()) {
                        townBlock.getPlotObjectGroup().getTownBlocks().stream().forEach(tb -> {
                            // Remove Resident.
                            tb.setResident(null);
                            // Set to NotForSale.
                            tb.setPlotPrice(-1);
                            // Re-set the plot permissions while maintaining plot type.
                            tb.setType(townBlock.getType());
                            // Save townblock.
                            tb.save();
                        });
                        TownyMessaging.sendMsg(player, Translatable.of("msg_plot_evict_group", townBlock.getPlotObjectGroup().getName()));
                        return true;
                    }
                    // Remove Resident.
                    townBlock.setResident(null);
                    // Set to NotForSale.
                    townBlock.setPlotPrice(-1);
                    // Re-set the plot permissions while maintaining plot type.
                    townBlock.setType(townBlock.getType());
                    // Save townblock.
                    townBlock.save();
                    TownyMessaging.sendMsg(player, Translatable.of("msg_plot_evict"));
                }
            } else if (split[0].equalsIgnoreCase("unclaim")) {
                if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_UNCLAIM.getNode()))
                    throw new TownyException(Translatable.of("msg_err_command_disable"));
                if (split.length == 2 && split[1].equalsIgnoreCase("all")) {
                    // Start the unclaim task
                    new PlotClaim(plugin, player, resident, null, false, false, false).start();
                } else {
                    List<WorldCoord> selection = AreaSelectionUtil.selectWorldCoordArea(resident, new WorldCoord(world, Coord.parseCoord(player)), StringMgmt.remFirstArg(split));
                    selection = AreaSelectionUtil.filterOwnedBlocks(resident, selection);
                    if (selection.size() > 0) {
                        for (WorldCoord coord : selection) {
                            TownBlock block = coord.getTownBlock();
                            if (!block.hasPlotObjectGroup()) {
                                // Start the unclaim task
                                new PlotClaim(plugin, player, resident, selection, false, false, false).start();
                                return true;
                            }
                            // Get all the townblocks part of the group.
                            final List<WorldCoord> groupSelection = new ArrayList<>();
                            block.getPlotObjectGroup().getTownBlocks().forEach((tb) -> {
                                groupSelection.add(tb.getWorldCoord());
                            });
                            // Create confirmation.
                            Confirmation.runOnAccept(() -> {
                                new PlotClaim(Towny.getPlugin(), player, resident, groupSelection, false, false, false).start();
                            }).setTitle(Translatable.of("msg_plot_group_unclaim_confirmation", block.getPlotObjectGroup().getTownBlocks().size()).append(" " + Translatable.of("are_you_sure_you_want_to_continue"))).sendTo(player);
                            return true;
                        }
                    } else {
                        TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_empty_area_selection"));
                    }
                }
            } else if (split[0].equalsIgnoreCase("notforsale") || split[0].equalsIgnoreCase("nfs")) {
                if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_NOTFORSALE.getNode()))
                    throw new TownyException(Translatable.of("msg_err_command_disable"));
                List<WorldCoord> selection = AreaSelectionUtil.selectWorldCoordArea(resident, new WorldCoord(world, Coord.parseCoord(player)), StringMgmt.remFirstArg(split));
                selection = AreaSelectionUtil.filterPlotsForSale(selection);
                if (permSource.testPermission(player, PermissionNodes.TOWNY_ADMIN.getNode())) {
                    for (WorldCoord worldCoord : selection) {
                        if (worldCoord.getTownBlock().hasPlotObjectGroup()) {
                            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_belongs_to_group_plot_nfs", worldCoord));
                            return false;
                        }
                        setPlotForSale(resident, worldCoord, -1);
                    }
                    return true;
                }
                // The follow test will clean up the initial selection fairly well, the plotTestOwner later on in the setPlotForSale will ultimately stop any funny business.
                if (permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_ASMAYOR.getNode()) && (resident.hasTown() && townBlock.hasTown() && resident.getTown() == townBlock.getTownOrNull())) {
                    // Treat it as a mayor able to set their town's plots not for sale.
                    selection = AreaSelectionUtil.filterOwnedBlocks(resident.getTown(), selection);
                } else {
                    // Treat it as a resident making their own plots not for sale.
                    selection = AreaSelectionUtil.filterOwnedBlocks(resident, selection);
                }
                if (selection.isEmpty())
                    throw new TownyException(Translatable.of("msg_err_empty_area_selection"));
                // Set each WorldCoord in selection not for sale.
                for (WorldCoord worldCoord : selection) {
                    // Skip over any plots that are part of a PlotGroup.
                    if (worldCoord.getTownBlock().hasPlotObjectGroup()) {
                        TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_belongs_to_group_plot_nfs", worldCoord));
                        continue;
                    }
                    setPlotForSale(resident, worldCoord, -1);
                }
            } else if (split[0].equalsIgnoreCase("forsale") || split[0].equalsIgnoreCase("fs")) {
                if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_FORSALE.getNode()))
                    throw new TownyException(Translatable.of("msg_err_command_disable"));
                WorldCoord pos = new WorldCoord(world, Coord.parseCoord(player));
                Town town = townBlock.getTownOrNull();
                if (town == null)
                    throw new TownyException(Translatable.of("msg_err_empty_area_selection"));
                double plotPrice = town.getPlotTypePrice(townBlock.getType());
                if (split.length > 1) {
                    /*
						 * This is not a case of '/plot fs' and has a cost and/or an area selection involved.
						 */
                    // areaSelectPivot is how Towny handles the 'within' area selection when setting plots for sale.
                    // Will return -1 if the word 'within' is not found.
                    int areaSelectPivot = AreaSelectionUtil.getAreaSelectPivot(split);
                    List<WorldCoord> selection;
                    if (areaSelectPivot >= 0) {
                        // 'within' has been used in the command, make a selection.
                        selection = AreaSelectionUtil.selectWorldCoordArea(resident, new WorldCoord(world, Coord.parseCoord(player)), StringMgmt.subArray(split, areaSelectPivot + 1, split.length));
                        // The follow test will clean up the initial selection fairly well, the plotTestOwner later on in the setPlotForSale will ultimately stop any funny business.
                        if (permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_ASMAYOR.getNode()) && (resident.hasTown() && resident.getTown() == town)) {
                            // Treat it as a mayor able to put their town's plots for sale.
                            selection = AreaSelectionUtil.filterOwnedBlocks(resident.getTown(), selection);
                            // Filter out any resident-owned plots.
                            selection = AreaSelectionUtil.filterOutResidentBlocks(resident, selection);
                        } else {
                            // Treat it as a resident putting their own plots up for sale.
                            selection = AreaSelectionUtil.filterOwnedBlocks(resident, selection);
                        }
                        if (selection.isEmpty())
                            throw new TownyException(Translatable.of("msg_err_empty_area_selection"));
                    } else {
                        // No 'within' found so this will be a case of /plot fs $, add a single coord to selection.
                        selection = new ArrayList<>();
                        selection.add(pos);
                    }
                    // Check that it's not: /plot forsale within rect 3
                    if (areaSelectPivot != 1) {
                        try {
                            // command was 'plot fs $'
                            plotPrice = Double.parseDouble(split[1]);
                            if (plotPrice < 0) {
                                TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_negative_money"));
                                return true;
                            }
                        } catch (NumberFormatException e) {
                            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_error_must_be_num"));
                            return true;
                        }
                    }
                    // Set each WorldCoord in selection for sale.
                    for (WorldCoord worldCoord : selection) {
                        TownBlock tb = worldCoord.getTownBlock();
                        // Skip over any plots that are part of a PlotGroup.
                        if (tb.hasPlotObjectGroup()) {
                            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_belongs_to_group_plot_fs2", worldCoord));
                            continue;
                        }
                        // Otherwise continue on normally.
                        setPlotForSale(resident, worldCoord, plotPrice);
                    }
                } else {
                    // Skip over any plots that are part of a PlotGroup.
                    if (pos.getTownBlock().hasPlotObjectGroup()) {
                        TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_belongs_to_group_plot_fs2", pos));
                        return false;
                    }
                    // Otherwise continue on normally.
                    setPlotForSale(resident, pos, plotPrice);
                }
            } else if (split[0].equalsIgnoreCase("perm")) {
                parsePlotPermCommand(player, StringMgmt.remFirstArg(split));
            } else if (split[0].equalsIgnoreCase("info")) {
                if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_PERM_INFO.getNode()))
                    throw new TownyException(Translatable.of("msg_err_command_disable"));
                sendPlotInfo(player, StringMgmt.remFirstArg(split));
            } else if (split[0].equalsIgnoreCase("toggle")) {
                /*
					 * perm test in the plottoggle.
					 */
                // Test we are allowed to work on this plot
                // ignore the return as
                plotTestOwner(resident, townBlock);
                // Make sure that the player is only operating on a single plot and not a plotgroup.
                if (townBlock.hasPlotObjectGroup()) {
                    TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_belongs_to_group_toggle"));
                    return false;
                }
                plotToggle(player, new WorldCoord(world, Coord.parseCoord(player)).getTownBlock(), StringMgmt.remFirstArg(split));
            } else if (split[0].equalsIgnoreCase("set")) {
                split = StringMgmt.remFirstArg(split);
                if (split.length == 0 || split[0].equalsIgnoreCase("?")) {
                    HelpMenu.PLOT_SET.send(player);
                } else if (split.length > 0) {
                    if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_SET.getNode(split[0].toLowerCase())))
                        throw new TownyException(Translatable.of("msg_err_command_disable"));
                    // Make sure that the player is only operating on a plot object group if one exists.
                    if (townBlock.hasPlotObjectGroup()) {
                        TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_belongs_to_group_set"));
                        return false;
                    }
                    if (split[0].equalsIgnoreCase("perm")) {
                        // Set plot level permissions (if the plot owner) or
                        // Mayor/Assistant of the town.
                        // Test we are allowed to work on this plot
                        plotTestOwner(resident, townBlock);
                        setTownBlockPermissions(player, townBlock.getTownBlockOwner(), townBlock, StringMgmt.remFirstArg(split));
                        return true;
                    } else if (split[0].equalsIgnoreCase("name")) {
                        // Test we are allowed to work on this plot
                        plotTestOwner(resident, townBlock);
                        if (split.length == 1) {
                            townBlock.setName("");
                            TownyMessaging.sendMsg(player, Translatable.of("msg_plot_name_removed"));
                            townBlock.save();
                            return true;
                        }
                        String newName = StringMgmt.join(StringMgmt.remFirstArg(split), "_");
                        // Test if the plot name contains invalid characters.
                        if (!NameValidation.isBlacklistName(newName)) {
                            townBlock.setName(newName);
                            // townBlock.setChanged(true);
                            townBlock.save();
                            TownyMessaging.sendMsg(player, Translatable.of("msg_plot_name_set_to", townBlock.getName()));
                        } else {
                            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_invalid_name"));
                        }
                        return true;
                    } else if (split[0].equalsIgnoreCase("outpost")) {
                        if (TownySettings.isAllowingOutposts()) {
                            if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWN_CLAIM_OUTPOST.getNode()))
                                throw new TownyException(Translatable.of("msg_err_command_disable"));
                            // Test we are allowed to work on this plot
                            plotTestOwner(resident, townBlock);
                            Town town = townBlock.getTownOrNull();
                            TownyWorld townyWorld = townBlock.getWorld();
                            boolean isAdmin = permSource.isTownyAdmin(player);
                            Coord key = Coord.parseCoord(plugin.getCache(player).getLastLocation());
                            if (OutpostUtil.OutpostTests(town, resident, townyWorld, key, isAdmin, true)) {
                                // Test if they can pay.
                                if (TownyEconomyHandler.isActive() && !town.getAccount().canPayFromHoldings(TownySettings.getOutpostCost()))
                                    throw new TownyException(Translatable.of("msg_err_cannot_afford_to_set_outpost"));
                                // Create a confirmation for setting outpost.
                                Confirmation.runOnAccept(() -> {
                                    // Make them pay.
                                    if (TownyEconomyHandler.isActive() && TownySettings.getOutpostCost() > 0 && !town.getAccount().withdraw(TownySettings.getOutpostCost(), "Plot Set Outpost")) {
                                        TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_cannot_afford_to_set_outpost"));
                                        return;
                                    }
                                    // Set the outpost spawn and display feedback.
                                    town.addOutpostSpawn(player.getLocation());
                                    TownyMessaging.sendMsg(player, Translatable.of("msg_plot_set_cost", TownyEconomyHandler.getFormattedBalance(TownySettings.getOutpostCost()), Translatable.of("outpost")));
                                }).setTitle(Translatable.of("msg_confirm_purchase", TownyEconomyHandler.getFormattedBalance(TownySettings.getOutpostCost()))).sendTo(player);
                            }
                        }
                        return true;
                    } else if (TownyCommandAddonAPI.hasCommand(CommandType.PLOT_SET, split[0])) {
                        TownyCommandAddonAPI.getAddonCommand(CommandType.PLOT_SET, split[0]).execute(player, "plot", split);
                        return true;
                    }
                    try {
                        String plotTypeName = split[0];
                        // Handle type being reset
                        if (plotTypeName.equalsIgnoreCase("reset"))
                            plotTypeName = "default";
                        TownBlockType townBlockType = TownBlockTypeHandler.getType(plotTypeName);
                        if (townBlockType == null)
                            throw new TownyException(Translatable.of("msg_err_not_block_type"));
                        try {
                            // Test we are allowed to work on this plot
                            // ignore the return as we
                            plotTestOwner(resident, townBlock);
                        // are only checking for an
                        // exception
                        } catch (TownyException e) {
                            TownyMessaging.sendErrorMsg(player, e.getMessage(player));
                            return false;
                        }
                        if (TownBlockType.ARENA.equals(townBlockType) && TownySettings.getOutsidersPreventPVPToggle()) {
                            for (Player target : Bukkit.getOnlinePlayers()) {
                                if (!townBlock.getTownOrNull().hasResident(target) && !player.getName().equals(target.getName()) && townBlock.getWorldCoord().equals(WorldCoord.parseWorldCoord(target)))
                                    throw new TownyException(Translatable.of("msg_cant_toggle_pvp_outsider_in_plot"));
                            }
                        }
                        PlotPreChangeTypeEvent preEvent = new PlotPreChangeTypeEvent(townBlockType, townBlock, resident);
                        BukkitTools.getPluginManager().callEvent(preEvent);
                        if (preEvent.isCancelled()) {
                            TownyMessaging.sendErrorMsg(player, preEvent.getCancelMessage());
                            return false;
                        }
                        double cost = townBlockType.getData().getCost();
                        // Test if we can pay first to throw an exception.
                        if (cost > 0 && TownyEconomyHandler.isActive() && !resident.getAccount().canPayFromHoldings(cost))
                            throw new TownyException(Translatable.of("msg_err_cannot_afford_plot_set_type_cost", townBlockType, TownyEconomyHandler.getFormattedBalance(cost)));
                        // Handle payment via a confirmation to avoid suprise costs.
                        if (cost > 0 && TownyEconomyHandler.isActive()) {
                            Confirmation.runOnAccept(() -> {
                                if (!resident.getAccount().withdraw(cost, String.format("Plot set to %s", townBlockType))) {
                                    TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_cannot_afford_plot_set_type_cost", townBlockType, TownyEconomyHandler.getFormattedBalance(cost)));
                                    return;
                                }
                                TownyMessaging.sendMsg(resident, Translatable.of("msg_plot_set_cost", TownyEconomyHandler.getFormattedBalance(cost), townBlockType));
                                try {
                                    townBlock.setType(townBlockType, resident);
                                } catch (TownyException e) {
                                    TownyMessaging.sendErrorMsg(resident, e.getMessage(player));
                                    return;
                                }
                                TownyMessaging.sendMsg(player, Translatable.of("msg_plot_set_type", townBlockType));
                            }).setTitle(Translatable.of("msg_confirm_purchase", TownyEconomyHandler.getFormattedBalance(cost))).sendTo(BukkitTools.getPlayerExact(resident.getName()));
                        // No cost or economy so no confirmation.
                        } else {
                            townBlock.setType(townBlockType, resident);
                            TownyMessaging.sendMsg(player, Translatable.of("msg_plot_set_type", plotTypeName));
                        }
                    } catch (TownyException te) {
                        TownyMessaging.sendErrorMsg(player, te.getMessage(player));
                    }
                } else {
                    HelpMenu.PLOT_SET.send(player);
                }
            } else if (split[0].equalsIgnoreCase("clear")) {
                if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_CLEAR.getNode()))
                    throw new TownyException(Translatable.of("msg_err_command_disable"));
                if (townBlock != null) {
                    if (!townBlock.getWorld().isUsingPlotManagementMayorDelete())
                        throw new TownyException(Translatable.of("msg_err_plot_clear_disabled_in_this_world"));
                    /*
						 * Only allow mayors or plot owners to use this command.
						 * This will throw an exception if the player isn't a mayor or owner of the plot. 
						 */
                    plotTestOwner(resident, townBlock);
                    PlotPreClearEvent preEvent = new PlotPreClearEvent(townBlock);
                    BukkitTools.getPluginManager().callEvent(preEvent);
                    if (preEvent.isCancelled()) {
                        TownyMessaging.sendErrorMsg(player, preEvent.getCancelMessage());
                        return false;
                    }
                    EnumSet<Material> materialsToDelete = TownyAPI.getInstance().getTownyWorld(world).getPlotManagementMayorDelete();
                    if (!materialsToDelete.isEmpty()) {
                        TownyRegenAPI.deleteMaterialsFromTownBlock(townBlock, materialsToDelete);
                        TownyMessaging.sendMsg(player, Translatable.of("msg_clear_plot_material", StringMgmt.join(materialsToDelete, ", ")));
                    }
                    // Raise an event for the claim
                    BukkitTools.getPluginManager().callEvent(new PlotClearEvent(townBlock));
                } else {
                    // Shouldn't ever reach here as a null townBlock should
                    // be caught already in WorldCoord.
                    TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_empty_area_selection"));
                }
            } else if (split[0].equalsIgnoreCase("group")) {
                return handlePlotGroupCommand(StringMgmt.remFirstArg(split), player);
            } else if (split[0].equalsIgnoreCase("jailcell")) {
                parsePlotJailCell(player, TownyAPI.getInstance().getTownBlock(player), StringMgmt.remFirstArg(split));
                return true;
            } else if (split[0].equalsIgnoreCase("trust")) {
                if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_TRUST.getNode()))
                    throw new TownyException(Translatable.of("msg_err_command_disable"));
                parsePlotTrustCommand(player, StringMgmt.remFirstArg(split));
                return true;
            } else if (TownyCommandAddonAPI.hasCommand(CommandType.PLOT, split[0])) {
                TownyCommandAddonAPI.getAddonCommand(CommandType.PLOT, split[0]).execute(player, "plot", split);
            } else
                throw new TownyException(Translatable.of("msg_err_invalid_property", split[0]));
        } catch (TownyException x) {
            TownyMessaging.sendErrorMsg(player, x.getMessage(player));
        }
    }
    return true;
}
Also used : Arrays(java.util.Arrays) Resident(com.palmergames.bukkit.towny.object.Resident) TownBlockType(com.palmergames.bukkit.towny.object.TownBlockType) Translatable(com.palmergames.bukkit.towny.object.Translatable) TownBlockTypeHandler(com.palmergames.bukkit.towny.object.TownBlockTypeHandler) Player(org.bukkit.entity.Player) PlotSetForSaleEvent(com.palmergames.bukkit.towny.event.plot.PlotSetForSaleEvent) TownBlockOwner(com.palmergames.bukkit.towny.object.TownBlockOwner) PlotTrustAddEvent(com.palmergames.bukkit.towny.event.plot.PlotTrustAddEvent) CooldownTimerTask(com.palmergames.bukkit.towny.tasks.CooldownTimerTask) TownyFormatter(com.palmergames.bukkit.towny.TownyFormatter) OutpostUtil(com.palmergames.bukkit.towny.utils.OutpostUtil) NameUtil(com.palmergames.bukkit.towny.utils.NameUtil) PlotClaim(com.palmergames.bukkit.towny.tasks.PlotClaim) Material(org.bukkit.Material) EnumSet(java.util.EnumSet) Bukkit(org.bukkit.Bukkit) TownBlockSettingsChangedEvent(com.palmergames.bukkit.towny.event.TownBlockSettingsChangedEvent) TownyRegenAPI(com.palmergames.bukkit.towny.regen.TownyRegenAPI) TownyPermissionSource(com.palmergames.bukkit.towny.permissions.TownyPermissionSource) CommandSender(org.bukkit.command.CommandSender) TownyPermission(com.palmergames.bukkit.towny.object.TownyPermission) NameValidation(com.palmergames.bukkit.util.NameValidation) TownyWorld(com.palmergames.bukkit.towny.object.TownyWorld) SpawnPointLocation(com.palmergames.bukkit.towny.object.SpawnPointLocation) BukkitTools(com.palmergames.bukkit.util.BukkitTools) UUID(java.util.UUID) CombatUtil(com.palmergames.bukkit.towny.utils.CombatUtil) Coord(com.palmergames.bukkit.towny.object.Coord) PlotToggleFireEvent(com.palmergames.bukkit.towny.event.plot.toggle.PlotToggleFireEvent) PlotClearEvent(com.palmergames.bukkit.towny.event.PlotClearEvent) List(java.util.List) Optional(java.util.Optional) Command(org.bukkit.command.Command) Towny(com.palmergames.bukkit.towny.Towny) TownyMessaging(com.palmergames.bukkit.towny.TownyMessaging) PlotNotForSaleEvent(com.palmergames.bukkit.towny.event.plot.PlotNotForSaleEvent) WorldCoord(com.palmergames.bukkit.towny.object.WorldCoord) AreaSelectionUtil(com.palmergames.bukkit.towny.utils.AreaSelectionUtil) PlotPreClearEvent(com.palmergames.bukkit.towny.event.PlotPreClearEvent) PlotToggleExplosionEvent(com.palmergames.bukkit.towny.event.plot.toggle.PlotToggleExplosionEvent) PlotTrustRemoveEvent(com.palmergames.bukkit.towny.event.plot.PlotTrustRemoveEvent) PlotTogglePvpEvent(com.palmergames.bukkit.towny.event.plot.toggle.PlotTogglePvpEvent) TownyUniverse(com.palmergames.bukkit.towny.TownyUniverse) ArrayList(java.util.ArrayList) PlotPreChangeTypeEvent(com.palmergames.bukkit.towny.event.PlotPreChangeTypeEvent) TownyCommandAddonAPI(com.palmergames.bukkit.towny.TownyCommandAddonAPI) HUDManager(com.palmergames.bukkit.towny.huds.HUDManager) PlotGroup(com.palmergames.bukkit.towny.object.PlotGroup) PlotToggleMobsEvent(com.palmergames.bukkit.towny.event.plot.toggle.PlotToggleMobsEvent) CooldownType(com.palmergames.bukkit.towny.tasks.CooldownTimerTask.CooldownType) ChatTools(com.palmergames.bukkit.util.ChatTools) PermissionData(com.palmergames.bukkit.towny.object.PermissionData) Town(com.palmergames.bukkit.towny.object.Town) PermissionGUIUtil(com.palmergames.bukkit.towny.utils.PermissionGUIUtil) StringMgmt(com.palmergames.util.StringMgmt) Colors(com.palmergames.bukkit.util.Colors) TownyPermissionChange(com.palmergames.bukkit.towny.object.TownyPermissionChange) TownyEconomyHandler(com.palmergames.bukkit.towny.TownyEconomyHandler) CommandExecutor(org.bukkit.command.CommandExecutor) TownyAPI(com.palmergames.bukkit.towny.TownyAPI) CommandType(com.palmergames.bukkit.towny.TownyCommandAddonAPI.CommandType) AlreadyRegisteredException(com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException) PermissionNodes(com.palmergames.bukkit.towny.permissions.PermissionNodes) TownBlock(com.palmergames.bukkit.towny.object.TownBlock) Confirmation(com.palmergames.bukkit.towny.confirmations.Confirmation) TownySettings(com.palmergames.bukkit.towny.TownySettings) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) Collections(java.util.Collections) Jail(com.palmergames.bukkit.towny.object.jail.Jail) TownBlockType(com.palmergames.bukkit.towny.object.TownBlockType) AlreadyRegisteredException(com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException) ArrayList(java.util.ArrayList) PlotPreClearEvent(com.palmergames.bukkit.towny.event.PlotPreClearEvent) Town(com.palmergames.bukkit.towny.object.Town) Resident(com.palmergames.bukkit.towny.object.Resident) List(java.util.List) ArrayList(java.util.ArrayList) PlotClearEvent(com.palmergames.bukkit.towny.event.PlotClearEvent) TownyPermissionSource(com.palmergames.bukkit.towny.permissions.TownyPermissionSource) TownyWorld(com.palmergames.bukkit.towny.object.TownyWorld) PlotPreChangeTypeEvent(com.palmergames.bukkit.towny.event.PlotPreChangeTypeEvent) TownBlock(com.palmergames.bukkit.towny.object.TownBlock) Player(org.bukkit.entity.Player) EnumSet(java.util.EnumSet) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) PlotClaim(com.palmergames.bukkit.towny.tasks.PlotClaim) Coord(com.palmergames.bukkit.towny.object.Coord) WorldCoord(com.palmergames.bukkit.towny.object.WorldCoord) WorldCoord(com.palmergames.bukkit.towny.object.WorldCoord)

Example 2 with PlotPreChangeTypeEvent

use of com.palmergames.bukkit.towny.event.PlotPreChangeTypeEvent in project Towny by TownyAdvanced.

the class PlotCommand method handlePlotGroupCommand.

private boolean handlePlotGroupCommand(String[] split, Player player) throws TownyException {
    TownyPermissionSource permSource = TownyUniverse.getInstance().getPermissionSource();
    Resident resident = getResidentOrThrow(player.getUniqueId());
    TownBlock townBlock = TownyAPI.getInstance().getTownBlock(player);
    if (townBlock == null)
        throw new TownyException(Translatable.of("msg_not_claimed_1"));
    Town town = townBlock.getTownOrNull();
    if (town == null)
        throw new TownyException(Translatable.of("msg_not_claimed_1"));
    // Test we are allowed to work on this plot
    // If this fails it will trigger a TownyException.
    plotTestOwner(resident, townBlock);
    if (split.length <= 0 || split[0].equalsIgnoreCase("?")) {
        HelpMenu.PLOT_GROUP_HELP.send(player);
        if (townBlock.hasPlotObjectGroup())
            TownyMessaging.sendMsg(player, Translatable.of("status_plot_group_name_and_size", townBlock.getPlotObjectGroup().getName(), townBlock.getPlotObjectGroup().getTownBlocks().size()));
        return true;
    }
    if (split[0].equalsIgnoreCase("add") || split[0].equalsIgnoreCase("new") || split[0].equalsIgnoreCase("create")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_ADD.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        if (split.length == 1) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_you_must_specify_a_group_name"));
            return false;
        }
        if (split.length == 2) {
            String plotGroupName = NameValidation.filterName(split[1]);
            plotGroupName = NameValidation.filterCommas(plotGroupName);
            if (town.hasPlotGroupName(plotGroupName)) {
                TownBlockType groupType = town.getPlotObjectGroupFromName(plotGroupName).getTownBlockType();
                if (townBlock.getType() != groupType)
                    throw new TownyException(Translatable.of("msg_err_this_townblock_doesnt_match_the_groups_type", groupType.getName()));
            }
            if (townBlock.hasPlotObjectGroup()) {
                // Already has a PlotGroup and it is the same name being used to re-add.
                if (townBlock.getPlotObjectGroup().getName().equalsIgnoreCase(plotGroupName)) {
                    TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_this_plot_is_already_part_of_the_plot_group_x", plotGroupName));
                    return false;
                }
                final String name = plotGroupName;
                // Already has a PlotGroup, ask if they want to transfer from one group to another.
                Confirmation.runOnAccept(() -> {
                    PlotGroup oldGroup = townBlock.getPlotObjectGroup();
                    oldGroup.removeTownBlock(townBlock);
                    if (oldGroup.getTownBlocks().isEmpty()) {
                        String oldName = oldGroup.getName();
                        town.removePlotGroup(oldGroup);
                        TownyUniverse.getInstance().getDataSource().removePlotGroup(oldGroup);
                        TownyMessaging.sendMsg(player, Translatable.of("msg_plotgroup_deleted", oldName));
                    } else
                        oldGroup.save();
                    createOrAddOnToPlotGroup(townBlock, town, name);
                    TownyMessaging.sendMsg(player, Translatable.of("msg_townblock_transferred_from_x_to_x_group", oldGroup.getName(), townBlock.getPlotObjectGroup().getName()));
                }).setTitle(Translatable.of("msg_plot_group_already_exists_did_you_want_to_transfer", townBlock.getPlotObjectGroup().getName(), split[1])).sendTo(player);
            } else {
                // Create a brand new plot group.
                createOrAddOnToPlotGroup(townBlock, town, plotGroupName);
                TownyMessaging.sendMsg(player, Translatable.of("msg_plot_was_put_into_group_x", townBlock.getX(), townBlock.getZ(), townBlock.getPlotObjectGroup().getName()));
            }
        } else {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_group_name_required"));
            return false;
        }
    } else if (split[0].equalsIgnoreCase("delete")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_DELETE.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        if (!townBlock.hasPlotObjectGroup()) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        Confirmation.runOnAccept(() -> {
            PlotGroup group = townBlock.getPlotObjectGroup();
            String name = group.getName();
            town.removePlotGroup(group);
            TownyUniverse.getInstance().getDataSource().removePlotGroup(group);
            TownyMessaging.sendMsg(player, Translatable.of("msg_plotgroup_deleted", name));
        }).sendTo(player);
    } else if (split[0].equalsIgnoreCase("remove")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_REMOVE.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        if (!townBlock.hasPlotObjectGroup()) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        PlotGroup group = townBlock.getPlotObjectGroup();
        String name = group.getName();
        // Remove the plot from the group.
        group.removeTownBlock(townBlock);
        // Detach group from townblock.
        townBlock.removePlotObjectGroup();
        // Save
        townBlock.save();
        TownyMessaging.sendMsg(player, Translatable.of("msg_plot_was_removed_from_group_x", townBlock.getX(), townBlock.getZ(), name));
        if (group.getTownBlocks().isEmpty()) {
            town.removePlotGroup(group);
            TownyUniverse.getInstance().getDataSource().removePlotGroup(group);
            TownyMessaging.sendMsg(player, Translatable.of("msg_plotgroup_empty_deleted", name));
        }
    } else if (split[0].equalsIgnoreCase("rename")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_RENAME.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        if (!townBlock.hasPlotObjectGroup()) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        if (split.length == 1) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_group_name_required"));
            return false;
        }
        String newName = split[1];
        String oldName = townBlock.getPlotObjectGroup().getName();
        // Change name;
        TownyUniverse.getInstance().getDataSource().renameGroup(townBlock.getPlotObjectGroup(), newName);
        TownyMessaging.sendMsg(player, Translatable.of("msg_plot_renamed_from_x_to_y", oldName, newName));
    } else if (split[0].equalsIgnoreCase("forsale") || split[0].equalsIgnoreCase("fs")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_FORSALE.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        // This means the player wants to fs the plot group they are in.
        PlotGroup group = townBlock.getPlotObjectGroup();
        if (group == null) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        if (split.length < 2) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_group_specify_price"));
            return false;
        }
        int price = 0;
        try {
            price = Integer.parseInt(split[1]);
        } catch (NumberFormatException e) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_error_must_be_num"));
            return false;
        }
        if (price < 0) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_negative_money"));
            return false;
        }
        group.setPrice(price);
        // Save
        group.save();
        TownyMessaging.sendPrefixedTownMessage(town, Translatable.of("msg_player_put_group_up_for_sale", player.getName(), group.getName(), TownyEconomyHandler.getFormattedBalance(group.getPrice())));
    } else if (split[0].equalsIgnoreCase("notforsale") || split[0].equalsIgnoreCase("nfs")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_NOTFORSALE.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        // This means the player wants to nfs the plot group they are in.
        PlotGroup group = townBlock.getPlotObjectGroup();
        if (group == null) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        group.setPrice(-1);
        // Save
        group.save();
        TownyMessaging.sendPrefixedTownMessage(town, Translatable.of("msg_player_made_group_not_for_sale", player.getName(), group.getName()));
    } else if (split[0].equalsIgnoreCase("toggle")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_TOGGLE.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        if (townBlock.getPlotObjectGroup() == null) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        // Create confirmation.
        PlotGroup plotGroup = townBlock.getPlotObjectGroup();
        Confirmation.runOnAccept(() -> {
            // Perform the toggle.
            new PlotCommand(Towny.getPlugin()).plotGroupToggle(player, plotGroup, StringMgmt.remArgs(split, 1));
        }).setTitle(Translatable.of("msg_plot_group_toggle_confirmation", townBlock.getPlotObjectGroup().getTownBlocks().size()).append(" " + Translatable.of("are_you_sure_you_want_to_continue"))).sendTo(player);
        return true;
    } else if (split[0].equalsIgnoreCase("set")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_SET.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        // Check if group is present.
        if (townBlock.getPlotObjectGroup() == null) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        TownBlockOwner townBlockOwner = townBlock.getTownBlockOwner();
        if (split.length < 2) {
            TownyMessaging.sendMessage(player, ChatTools.formatTitle("/plot group set"));
            if (townBlockOwner instanceof Town)
                TownyMessaging.sendMessage(player, ChatTools.formatCommand("Level", "[resident/nation/ally/outsider]", "", ""));
            if (townBlockOwner instanceof Resident)
                TownyMessaging.sendMessage(player, ChatTools.formatCommand("Level", "[friend/town/ally/outsider]", "", ""));
            TownyMessaging.sendMessage(player, ChatTools.formatCommand("Type", "[build/destroy/switch/itemuse]", "", ""));
            TownyMessaging.sendMessage(player, ChatTools.formatCommand("/plot group set", "perm", "[on/off]", "Toggle all permissions"));
            TownyMessaging.sendMessage(player, ChatTools.formatCommand("/plot group set", "perm", "[level/type] [on/off]", ""));
            TownyMessaging.sendMessage(player, ChatTools.formatCommand("/plot group set", "perm", "[level] [type] [on/off]", ""));
            TownyMessaging.sendMessage(player, ChatTools.formatCommand("/plot group set", "perm", "reset", ""));
            TownyMessaging.sendMessage(player, ChatTools.formatCommand("Eg", "/plot group set perm", "friend build on", ""));
            TownyMessaging.sendMessage(player, ChatTools.formatCommand("/plot group set", "[townblocktype]", "", "Farm, Wilds, Bank, Embassy, etc."));
            return false;
        }
        if (split[1].equalsIgnoreCase("perm")) {
            // Set plot level permissions (if the plot owner) or
            // Mayor/Assistant of the town.
            PlotGroup plotGroup = townBlock.getPlotObjectGroup();
            Runnable permHandler = () -> {
                // setTownBlockPermissions returns a towny permission change object
                TownyPermissionChange permChange = PlotCommand.setTownBlockPermissions(player, townBlockOwner, townBlock, StringMgmt.remArgs(split, 2));
                // If the perm change object is not null
                if (permChange != null) {
                    plotGroup.getPermissions().change(permChange);
                    plotGroup.getTownBlocks().stream().forEach(tb -> {
                        tb.setPermissions(plotGroup.getPermissions().toString());
                        tb.setChanged(!tb.getPermissions().toString().equals(town.getPermissions().toString()));
                        tb.save();
                        // Change settings event
                        TownBlockSettingsChangedEvent event = new TownBlockSettingsChangedEvent(tb);
                        Bukkit.getServer().getPluginManager().callEvent(event);
                    });
                    plugin.resetCache();
                    TownyPermission perm = plotGroup.getPermissions();
                    TownyMessaging.sendMessage(player, Translatable.of("msg_set_perms").forLocale(player));
                    TownyMessaging.sendMessage(player, (Colors.Green + Translatable.of("status_perm").forLocale(player) + " " + ((townBlockOwner instanceof Resident) ? perm.getColourString().replace("n", "t") : perm.getColourString().replace("f", "r"))));
                    TownyMessaging.sendMessage(player, Colors.Green + Translatable.of("status_pvp").forLocale(player) + " " + (!(CombatUtil.preventPvP(townBlock.getWorld(), townBlock)) ? Colors.Red + "ON" : Colors.LightGreen + "OFF") + Colors.Green + Translatable.of("explosions").forLocale(player) + " " + ((perm.explosion) ? Colors.Red + "ON" : Colors.LightGreen + "OFF") + Colors.Green + Translatable.of("firespread").forLocale(player) + " " + ((perm.fire) ? Colors.Red + "ON" : Colors.LightGreen + "OFF") + Colors.Green + Translatable.of("mobspawns").forLocale(player) + " " + ((perm.mobs) ? Colors.Red + "ON" : Colors.LightGreen + "OFF"));
                }
            };
            // Create confirmation.
            Confirmation.runOnAccept(permHandler).setTitle(Translatable.of("msg_plot_group_set_perm_confirmation", townBlock.getPlotObjectGroup().getTownBlocks().size()).append(" " + Translatable.of("are_you_sure_you_want_to_continue"))).sendTo(player);
            return true;
        }
        /*
			 * After all other set commands are tested for we attempt to set the townblocktype.
			 */
        String plotTypeName = split[1];
        // Stop setting plot groups to Jail plot, because that would set a spawn point for each plot in the location of the player.
        if (plotTypeName.equalsIgnoreCase("jail")) {
            throw new TownyException(Translatable.of("msg_err_cannot_set_group_to_jail"));
        }
        // Handle type being reset
        if (plotTypeName.equalsIgnoreCase("reset"))
            plotTypeName = "default";
        TownBlockType type = TownBlockTypeHandler.getType(plotTypeName);
        if (type == null)
            throw new TownyException(Translatable.of("msg_err_not_block_type"));
        for (TownBlock tb : townBlock.getPlotObjectGroup().getTownBlocks()) {
            try {
                // Test we are allowed to work on this plot
                // ignore the return as we
                plotTestOwner(resident, townBlock);
            // are only checking for an
            // exception
            } catch (TownyException e) {
                TownyMessaging.sendErrorMsg(resident, e.getMessage(player));
                return false;
            }
            if (TownBlockType.ARENA.equals(type) && TownySettings.getOutsidersPreventPVPToggle()) {
                for (Player target : Bukkit.getOnlinePlayers()) {
                    if (!town.hasResident(target) && !player.getName().equals(target.getName()) && tb.getWorldCoord().equals(WorldCoord.parseWorldCoord(target)))
                        throw new TownyException(Translatable.of("msg_cant_toggle_pvp_outsider_in_plot"));
                }
            }
            // Allow for PlotPreChangeTypeEvent to trigger
            PlotPreChangeTypeEvent preEvent = new PlotPreChangeTypeEvent(type, tb, resident);
            BukkitTools.getPluginManager().callEvent(preEvent);
            // If any one of the townblocks is not allowed to be set, cancel setting all of them.
            if (preEvent.isCancelled()) {
                TownyMessaging.sendErrorMsg(player, preEvent.getCancelMessage());
                return false;
            }
        }
        int amount = townBlock.getPlotObjectGroup().getTownBlocks().size();
        double cost = type.getCost() * amount;
        try {
            // Test if we can pay first to throw an exception.
            if (cost > 0 && TownyEconomyHandler.isActive() && !resident.getAccount().canPayFromHoldings(cost))
                throw new TownyException(Translatable.of("msg_err_cannot_afford_plot_set_type_cost", type, TownyEconomyHandler.getFormattedBalance(cost)));
            // Handle payment via a confirmation to avoid suprise costs.
            if (cost > 0 && TownyEconomyHandler.isActive()) {
                Confirmation.runOnAccept(() -> {
                    if (!resident.getAccount().withdraw(cost, String.format("Plot (" + amount + ") set to %s", type))) {
                        TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_cannot_afford_plot_set_type_cost", type, TownyEconomyHandler.getFormattedBalance(cost)));
                        return;
                    }
                    TownyMessaging.sendMsg(resident, Translatable.of("msg_plot_set_cost", TownyEconomyHandler.getFormattedBalance(cost), type));
                    for (TownBlock tb : townBlock.getPlotObjectGroup().getTownBlocks()) {
                        try {
                            tb.setType(type, resident);
                        } catch (TownyException ignored) {
                        // Cannot be set to jail type as a group.
                        }
                    }
                    TownyMessaging.sendMsg(player, Translatable.of("msg_set_group_type_to_x", type));
                }).setTitle(Translatable.of("msg_confirm_purchase", TownyEconomyHandler.getFormattedBalance(cost))).sendTo(BukkitTools.getPlayerExact(resident.getName()));
            // No cost or economy so no confirmation.
            } else {
                for (TownBlock tb : townBlock.getPlotObjectGroup().getTownBlocks()) tb.setType(type, resident);
                TownyMessaging.sendMsg(player, Translatable.of("msg_set_group_type_to_x", plotTypeName));
            }
        } catch (TownyException e) {
            TownyMessaging.sendErrorMsg(resident, e.getMessage(player));
        }
    } else if (split[0].equalsIgnoreCase("trust")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_TRUST.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        if (split.length < 3) {
            HelpMenu.PLOT_GROUP_TRUST_HELP.send(player);
            return true;
        }
        PlotGroup group = townBlock.getPlotObjectGroup();
        if (group == null) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        Resident trustedResident = TownyAPI.getInstance().getResident(split[2]);
        if (trustedResident == null || trustedResident.isNPC()) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_not_registered_1", split[2]));
            return false;
        }
        if (split[1].equalsIgnoreCase("add")) {
            if (group.hasTrustedResident(trustedResident)) {
                TownyMessaging.sendErrorMsg(player, Translatable.of("msg_already_trusted", trustedResident.getName(), Translatable.of("plotgroup_sing")));
                return false;
            }
            PlotTrustAddEvent event = new PlotTrustAddEvent(new ArrayList<>(group.getTownBlocks()), trustedResident, player);
            Bukkit.getPluginManager().callEvent(event);
            if (event.isCancelled()) {
                TownyMessaging.sendErrorMsg(player, event.getCancelMessage());
                return false;
            }
            group.addTrustedResident(trustedResident);
            plugin.deleteCache(trustedResident);
            TownyMessaging.sendMsg(player, Translatable.of("msg_trusted_added", trustedResident.getName(), Translatable.of("plotgroup_sing")));
            if (BukkitTools.isOnline(trustedResident.getName()) && !trustedResident.getName().equals(player.getName()))
                TownyMessaging.sendMsg(trustedResident, Translatable.of("msg_trusted_added_2", player.getName(), Translatable.of("plotgroup_sing"), group.getName()));
            return true;
        } else if (split[1].equalsIgnoreCase("remove")) {
            if (!group.hasTrustedResident(trustedResident)) {
                TownyMessaging.sendErrorMsg(player, Translatable.of("msg_not_trusted", trustedResident.getName(), Translatable.of("plotgroup_sing")));
                return false;
            }
            PlotTrustRemoveEvent event = new PlotTrustRemoveEvent(new ArrayList<>(group.getTownBlocks()), trustedResident, player);
            Bukkit.getPluginManager().callEvent(event);
            if (event.isCancelled()) {
                TownyMessaging.sendErrorMsg(player, event.getCancelMessage());
                return false;
            }
            group.removeTrustedResident(trustedResident);
            plugin.deleteCache(trustedResident);
            TownyMessaging.sendMsg(player, Translatable.of("msg_trusted_removed", trustedResident.getName(), Translatable.of("plotgroup_sing")));
            if (BukkitTools.isOnline(trustedResident.getName()) && !trustedResident.getName().equals(player.getName()))
                TownyMessaging.sendMsg(trustedResident, Translatable.of("msg_trusted_removed_2", player.getName(), Translatable.of("plotgroup_sing"), group.getName()));
            return true;
        } else {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_invalid_property", split[1]));
            return false;
        }
    } else if (split[0].equalsIgnoreCase("perm")) {
        if (!permSource.testPermission(player, PermissionNodes.TOWNY_COMMAND_PLOT_GROUP_PERM.getNode()))
            throw new TownyException(Translatable.of("msg_err_command_disable"));
        if (split.length < 2) {
            HelpMenu.PLOT_GROUP_PERM_HELP.send(player);
            return true;
        }
        PlotGroup group = townBlock.getPlotObjectGroup();
        if (group == null) {
            TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_plot_not_associated_with_a_group"));
            return false;
        }
        if (split[1].equalsIgnoreCase("gui")) {
            PermissionGUIUtil.openPermissionGUI(resident, townBlock);
        } else {
            if (split.length < 3) {
                HelpMenu.PLOT_GROUP_PERM_HELP.send(player);
                return true;
            }
            Resident overrideResident = TownyAPI.getInstance().getResident(split[2]);
            if (overrideResident == null || overrideResident.isNPC()) {
                TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_not_registered_1", split[2]));
                return true;
            }
            if (split[1].equalsIgnoreCase("add")) {
                if (group.getPermissionOverrides() != null && group.getPermissionOverrides().containsKey(overrideResident)) {
                    TownyMessaging.sendErrorMsg(player, Translatable.of("msg_overrides_already_set", overrideResident.getName(), Translatable.of("plotgroup_sing")));
                    return true;
                }
                group.putPermissionOverride(overrideResident, new PermissionData(PermissionGUIUtil.getDefaultTypes(), player.getName()));
                TownyMessaging.sendMsg(player, Translatable.of("msg_overrides_added", overrideResident.getName()));
            } else if (split[1].equalsIgnoreCase("remove")) {
                if (group.getPermissionOverrides() != null && !group.getPermissionOverrides().containsKey(overrideResident)) {
                    TownyMessaging.sendErrorMsg(player, Translatable.of("msg_no_overrides_set", overrideResident.getName(), Translatable.of("plotgroup_sing")));
                    return true;
                }
                group.removePermissionOverride(overrideResident);
                TownyMessaging.sendMsg(player, Translatable.of("msg_overrides_removed", overrideResident.getName()));
            } else {
                TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_invalid_property", split[1]));
                return false;
            }
        }
    } else {
        HelpMenu.PLOT_GROUP_HELP.send(player);
        if (townBlock.hasPlotObjectGroup())
            TownyMessaging.sendMsg(player, Translatable.of("status_plot_group_name_and_size", townBlock.getPlotObjectGroup().getName(), townBlock.getPlotObjectGroup().getTownBlocks().size()));
        return true;
    }
    return false;
}
Also used : TownBlockType(com.palmergames.bukkit.towny.object.TownBlockType) TownyPermission(com.palmergames.bukkit.towny.object.TownyPermission) Player(org.bukkit.entity.Player) ArrayList(java.util.ArrayList) PlotTrustRemoveEvent(com.palmergames.bukkit.towny.event.plot.PlotTrustRemoveEvent) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) PlotTrustAddEvent(com.palmergames.bukkit.towny.event.plot.PlotTrustAddEvent) Town(com.palmergames.bukkit.towny.object.Town) TownBlockOwner(com.palmergames.bukkit.towny.object.TownBlockOwner) TownyPermissionChange(com.palmergames.bukkit.towny.object.TownyPermissionChange) Resident(com.palmergames.bukkit.towny.object.Resident) TownBlockSettingsChangedEvent(com.palmergames.bukkit.towny.event.TownBlockSettingsChangedEvent) TownyPermissionSource(com.palmergames.bukkit.towny.permissions.TownyPermissionSource) PlotGroup(com.palmergames.bukkit.towny.object.PlotGroup) PlotPreChangeTypeEvent(com.palmergames.bukkit.towny.event.PlotPreChangeTypeEvent) TownBlock(com.palmergames.bukkit.towny.object.TownBlock) PermissionData(com.palmergames.bukkit.towny.object.PermissionData)

Aggregations

PlotPreChangeTypeEvent (com.palmergames.bukkit.towny.event.PlotPreChangeTypeEvent)2 TownBlockSettingsChangedEvent (com.palmergames.bukkit.towny.event.TownBlockSettingsChangedEvent)2 PlotTrustAddEvent (com.palmergames.bukkit.towny.event.plot.PlotTrustAddEvent)2 PlotTrustRemoveEvent (com.palmergames.bukkit.towny.event.plot.PlotTrustRemoveEvent)2 TownyException (com.palmergames.bukkit.towny.exceptions.TownyException)2 PermissionData (com.palmergames.bukkit.towny.object.PermissionData)2 PlotGroup (com.palmergames.bukkit.towny.object.PlotGroup)2 Resident (com.palmergames.bukkit.towny.object.Resident)2 Town (com.palmergames.bukkit.towny.object.Town)2 TownBlock (com.palmergames.bukkit.towny.object.TownBlock)2 TownBlockOwner (com.palmergames.bukkit.towny.object.TownBlockOwner)2 TownBlockType (com.palmergames.bukkit.towny.object.TownBlockType)2 TownyPermission (com.palmergames.bukkit.towny.object.TownyPermission)2 TownyPermissionChange (com.palmergames.bukkit.towny.object.TownyPermissionChange)2 TownyPermissionSource (com.palmergames.bukkit.towny.permissions.TownyPermissionSource)2 ArrayList (java.util.ArrayList)2 Player (org.bukkit.entity.Player)2 Towny (com.palmergames.bukkit.towny.Towny)1 TownyAPI (com.palmergames.bukkit.towny.TownyAPI)1 TownyCommandAddonAPI (com.palmergames.bukkit.towny.TownyCommandAddonAPI)1