Search in sources :

Example 1 with PlotFlag

use of com.plotsquared.core.plot.flag.PlotFlag in project PlotSquared by IntellectualSites.

the class Clear method execute.

@Override
public CompletableFuture<Boolean> execute(final PlotPlayer<?> player, String[] args, RunnableVal3<Command, Runnable, Runnable> confirm, RunnableVal2<Command, CommandResult> whenDone) throws CommandException {
    if (args.length != 0) {
        sendUsage(player);
        return CompletableFuture.completedFuture(false);
    }
    final Plot plot = check(player.getCurrentPlot(), TranslatableCaption.of("errors.not_in_plot"));
    Result eventResult = this.eventDispatcher.callClear(plot).getEventResult();
    if (eventResult == Result.DENY) {
        player.sendMessage(TranslatableCaption.of("events.event_denied"), Template.of("value", "Clear"));
        return CompletableFuture.completedFuture(true);
    }
    if (plot.getVolume() > Integer.MAX_VALUE) {
        player.sendMessage(TranslatableCaption.of("schematics.schematic_too_large"));
        return CompletableFuture.completedFuture(true);
    }
    boolean force = eventResult == Result.FORCE;
    checkTrue(force || plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, "plots.admin.command.clear"), TranslatableCaption.of("permission.no_plot_perms"));
    checkTrue(plot.getRunning() == 0, TranslatableCaption.of("errors.wait_for_timer"));
    checkTrue(force || !Settings.Done.RESTRICT_BUILDING || !DoneFlag.isDone(plot) || Permissions.hasPermission(player, "plots.continue"), TranslatableCaption.of("done.done_already_done"));
    confirm.run(this, () -> {
        if (Settings.Teleport.ON_CLEAR) {
            plot.getPlayersInPlot().forEach(playerInPlot -> plot.teleportPlayer(playerInPlot, TeleportCause.COMMAND_CLEAR, result -> {
            }));
        }
        BackupManager.backup(player, plot, () -> {
            final long start = System.currentTimeMillis();
            boolean result = plot.getPlotModificationManager().clear(true, false, player, () -> {
                plot.getPlotModificationManager().unlink();
                TaskManager.runTask(() -> {
                    plot.removeRunning();
                    // If the state changes, then mark it as no longer done
                    if (DoneFlag.isDone(plot)) {
                        PlotFlag<?, ?> plotFlag = plot.getFlagContainer().getFlag(DoneFlag.class);
                        PlotFlagRemoveEvent event = this.eventDispatcher.callFlagRemove(plotFlag, plot);
                        if (event.getEventResult() != Result.DENY) {
                            plot.removeFlag(event.getFlag());
                        }
                    }
                    if (!plot.getFlag(AnalysisFlag.class).isEmpty()) {
                        PlotFlag<?, ?> plotFlag = plot.getFlagContainer().getFlag(AnalysisFlag.class);
                        PlotFlagRemoveEvent event = this.eventDispatcher.callFlagRemove(plotFlag, plot);
                        if (event.getEventResult() != Result.DENY) {
                            plot.removeFlag(event.getFlag());
                        }
                    }
                    player.sendMessage(TranslatableCaption.of("working.clearing_done"), Template.of("amount", String.valueOf(System.currentTimeMillis() - start)), Template.of("plot", plot.getId().toString()));
                });
            });
            if (!result) {
                player.sendMessage(TranslatableCaption.of("errors.wait_for_timer"));
            } else {
                plot.addRunning();
            }
        });
    }, null);
    return CompletableFuture.completedFuture(true);
}
Also used : TeleportCause(com.plotsquared.core.events.TeleportCause) GlobalBlockQueue(com.plotsquared.core.queue.GlobalBlockQueue) PlotFlagRemoveEvent(com.plotsquared.core.events.PlotFlagRemoveEvent) Permissions(com.plotsquared.core.util.Permissions) NonNull(org.checkerframework.checker.nullness.qual.NonNull) Plot(com.plotsquared.core.plot.Plot) Inject(com.google.inject.Inject) TaskManager(com.plotsquared.core.util.task.TaskManager) CompletableFuture(java.util.concurrent.CompletableFuture) PlotFlag(com.plotsquared.core.plot.flag.PlotFlag) DoneFlag(com.plotsquared.core.plot.flag.implementations.DoneFlag) BackupManager(com.plotsquared.core.backup.BackupManager) Result(com.plotsquared.core.events.Result) RunnableVal3(com.plotsquared.core.util.task.RunnableVal3) PlotPlayer(com.plotsquared.core.player.PlotPlayer) TranslatableCaption(com.plotsquared.core.configuration.caption.TranslatableCaption) RunnableVal2(com.plotsquared.core.util.task.RunnableVal2) Settings(com.plotsquared.core.configuration.Settings) AnalysisFlag(com.plotsquared.core.plot.flag.implementations.AnalysisFlag) Template(net.kyori.adventure.text.minimessage.Template) EventDispatcher(com.plotsquared.core.util.EventDispatcher) Plot(com.plotsquared.core.plot.Plot) PlotFlagRemoveEvent(com.plotsquared.core.events.PlotFlagRemoveEvent) Result(com.plotsquared.core.events.Result)

Example 2 with PlotFlag

use of com.plotsquared.core.plot.flag.PlotFlag in project PlotSquared by IntellectualSites.

the class Plot method format.

public CompletableFuture<Caption> format(final Caption iInfo, PlotPlayer<?> player, final boolean full) {
    final CompletableFuture<Caption> future = new CompletableFuture<>();
    int num = this.getConnectedPlots().size();
    String alias = !this.getAlias().isEmpty() ? this.getAlias() : TranslatableCaption.of("info.none").getComponent(player);
    Location bot = this.getCorners()[0];
    PlotSquared.platform().worldUtil().getBiome(Objects.requireNonNull(this.getWorldName()), bot.getX(), bot.getZ(), biome -> {
        Component trusted = PlayerManager.getPlayerList(this.getTrusted(), player);
        Component members = PlayerManager.getPlayerList(this.getMembers(), player);
        Component denied = PlayerManager.getPlayerList(this.getDenied(), player);
        String seen;
        if (Settings.Enabled_Components.PLOT_EXPIRY && ExpireManager.IMP != null) {
            if (this.isOnline()) {
                seen = TranslatableCaption.of("info.now").getComponent(player);
            } else {
                int time = (int) (ExpireManager.IMP.getAge(this, false) / 1000);
                if (time != 0) {
                    seen = TimeUtil.secToTime(time);
                } else {
                    seen = TranslatableCaption.of("info.unknown").getComponent(player);
                }
            }
        } else {
            seen = TranslatableCaption.of("info.never").getComponent(player);
        }
        String description = this.getFlag(DescriptionFlag.class);
        if (description.isEmpty()) {
            description = TranslatableCaption.of("info.plot_no_description").getComponent(player);
        }
        Component flags;
        Collection<PlotFlag<?, ?>> flagCollection = this.getApplicableFlags(true);
        if (flagCollection.isEmpty()) {
            flags = MINI_MESSAGE.parse(TranslatableCaption.of("info.none").getComponent(player));
        } else {
            TextComponent.Builder flagBuilder = Component.text();
            String prefix = "";
            for (final PlotFlag<?, ?> flag : flagCollection) {
                Object value;
                if (flag instanceof DoubleFlag && !Settings.General.SCIENTIFIC) {
                    value = FLAG_DECIMAL_FORMAT.format(flag.getValue());
                } else {
                    value = flag.toString();
                }
                Component snip = MINI_MESSAGE.parse(prefix + CaptionUtility.format(player, TranslatableCaption.of("info.plot_flag_list").getComponent(player)), Template.of("flag", flag.getName()), Template.of("value", CaptionUtility.formatRaw(player, value.toString())));
                flagBuilder.append(snip);
                prefix = ", ";
            }
            flags = flagBuilder.build();
        }
        boolean build = this.isAdded(player.getUUID());
        Component owner;
        if (this.getOwner() == null) {
            owner = Component.text("unowned");
        } else if (this.getOwner().equals(DBFunc.SERVER)) {
            owner = Component.text(MINI_MESSAGE.stripTokens(TranslatableCaption.of("info.server").getComponent(player)));
        } else {
            owner = PlayerManager.getPlayerList(this.getOwners(), player);
        }
        Template headerTemplate = Template.of("header", TranslatableCaption.of("info.plot_info_header").getComponent(player));
        Template footerTemplate = Template.of("footer", TranslatableCaption.of("info.plot_info_footer").getComponent(player));
        Template areaTemplate;
        if (this.getArea() != null) {
            areaTemplate = Template.of("area", this.getArea().getWorldName() + (this.getArea().getId() == null ? "" : "(" + this.getArea().getId() + ")"));
        } else {
            areaTemplate = Template.of("area", TranslatableCaption.of("info.none").getComponent(player));
        }
        long creationDate = Long.parseLong(String.valueOf(timestamp));
        SimpleDateFormat sdf = new SimpleDateFormat(Settings.Timeformat.DATE_FORMAT);
        sdf.setTimeZone(TimeZone.getTimeZone(Settings.Timeformat.TIME_ZONE));
        String newDate = sdf.format(creationDate);
        Template idTemplate = Template.of("id", this.getId().toString());
        Template aliasTemplate = Template.of("alias", alias);
        Template numTemplate = Template.of("num", String.valueOf(num));
        Template descTemplate = Template.of("desc", description);
        Template biomeTemplate = Template.of("biome", biome.toString().toLowerCase());
        Template ownerTemplate = Template.of("owner", owner);
        Template membersTemplate = Template.of("members", members);
        Template playerTemplate = Template.of("player", player.getName());
        Template trustedTemplate = Template.of("trusted", trusted);
        Template helpersTemplate = Template.of("helpers", members);
        Template deniedTemplate = Template.of("denied", denied);
        Template seenTemplate = Template.of("seen", seen);
        Template flagsTemplate = Template.of("flags", flags);
        Template creationTemplate = Template.of("creationdate", newDate);
        Template buildTemplate = Template.of("build", String.valueOf(build));
        Template sizeTemplate = Template.of("size", String.valueOf(getConnectedPlots().size()));
        String component = iInfo.getComponent(player);
        if (component.contains("<rating>") || component.contains("<likes>")) {
            TaskManager.runTaskAsync(() -> {
                Template ratingTemplate;
                Template likesTemplate;
                if (Settings.Ratings.USE_LIKES) {
                    ratingTemplate = Template.of("rating", String.format("%.0f%%", Like.getLikesPercentage(this) * 100D));
                    likesTemplate = Template.of("likes", String.format("%.0f%%", Like.getLikesPercentage(this) * 100D));
                } else {
                    int max = 10;
                    if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) {
                        max = 8;
                    }
                    if (full && Settings.Ratings.CATEGORIES != null && Settings.Ratings.CATEGORIES.size() > 1) {
                        double[] ratings = this.getAverageRatings();
                        StringBuilder rating = new StringBuilder();
                        String prefix = "";
                        for (int i = 0; i < ratings.length; i++) {
                            rating.append(prefix).append(Settings.Ratings.CATEGORIES.get(i)).append('=').append(String.format("%.1f", ratings[i]));
                            prefix = ",";
                        }
                        ratingTemplate = Template.of("rating", rating.toString());
                    } else {
                        double rating = this.getAverageRating();
                        if (Double.isFinite(rating)) {
                            ratingTemplate = Template.of("rating", String.format("%.1f", rating) + '/' + max);
                        } else {
                            ratingTemplate = Template.of("rating", TranslatableCaption.of("info.none").getComponent(player));
                        }
                    }
                    likesTemplate = Template.of("likes", "N/A");
                }
                future.complete(StaticCaption.of(MINI_MESSAGE.serialize(MINI_MESSAGE.parse(iInfo.getComponent(player), headerTemplate, areaTemplate, idTemplate, aliasTemplate, numTemplate, descTemplate, biomeTemplate, ownerTemplate, membersTemplate, playerTemplate, trustedTemplate, helpersTemplate, deniedTemplate, seenTemplate, flagsTemplate, buildTemplate, ratingTemplate, creationTemplate, sizeTemplate, likesTemplate, footerTemplate))));
            });
            return;
        }
        future.complete(StaticCaption.of(MINI_MESSAGE.serialize(MINI_MESSAGE.parse(iInfo.getComponent(player), headerTemplate, areaTemplate, idTemplate, aliasTemplate, numTemplate, descTemplate, biomeTemplate, ownerTemplate, membersTemplate, playerTemplate, trustedTemplate, helpersTemplate, deniedTemplate, seenTemplate, flagsTemplate, buildTemplate, creationTemplate, sizeTemplate, footerTemplate))));
    });
    return future;
}
Also used : ServerPlotFlag(com.plotsquared.core.plot.flag.implementations.ServerPlotFlag) PlotFlag(com.plotsquared.core.plot.flag.PlotFlag) TextComponent(net.kyori.adventure.text.TextComponent) DoubleFlag(com.plotsquared.core.plot.flag.types.DoubleFlag) StaticCaption(com.plotsquared.core.configuration.caption.StaticCaption) Caption(com.plotsquared.core.configuration.caption.Caption) TranslatableCaption(com.plotsquared.core.configuration.caption.TranslatableCaption) Template(net.kyori.adventure.text.minimessage.Template) CompletableFuture(java.util.concurrent.CompletableFuture) TextComponent(net.kyori.adventure.text.TextComponent) Component(net.kyori.adventure.text.Component) SimpleDateFormat(java.text.SimpleDateFormat) Location(com.plotsquared.core.location.Location)

Example 3 with PlotFlag

use of com.plotsquared.core.plot.flag.PlotFlag in project PlotSquared by IntellectualSites.

the class PlotModificationManager method copy.

/**
 * Copy a plot to a location, both physically and the settings
 *
 * @param destination destination plot
 * @param actor       the actor associated with the copy
 * @return Future that completes with {@code true} if the copy was successful, else {@code false}
 */
public CompletableFuture<Boolean> copy(@NonNull final Plot destination, @Nullable PlotPlayer<?> actor) {
    final CompletableFuture<Boolean> future = new CompletableFuture<>();
    final PlotId offset = PlotId.of(destination.getId().getX() - this.plot.getId().getX(), destination.getId().getY() - this.plot.getId().getY());
    final Location db = destination.getBottomAbs();
    final Location ob = this.plot.getBottomAbs();
    final int offsetX = db.getX() - ob.getX();
    final int offsetZ = db.getZ() - ob.getZ();
    if (!this.plot.hasOwner()) {
        TaskManager.runTaskLater(() -> future.complete(false), TaskTime.ticks(1L));
        return future;
    }
    final Set<Plot> plots = this.plot.getConnectedPlots();
    for (final Plot plot : plots) {
        final Plot other = plot.getRelative(destination.getArea(), offset.getX(), offset.getY());
        if (other.hasOwner()) {
            TaskManager.runTaskLater(() -> future.complete(false), TaskTime.ticks(1L));
            return future;
        }
    }
    // world border
    destination.updateWorldBorder();
    // copy data
    for (final Plot plot : plots) {
        final Plot other = plot.getRelative(destination.getArea(), offset.getX(), offset.getY());
        other.getPlotModificationManager().create(plot.getOwner(), false);
        if (!plot.getFlagContainer().getFlagMap().isEmpty()) {
            final Collection<PlotFlag<?, ?>> existingFlags = other.getFlags();
            other.getFlagContainer().clearLocal();
            other.getFlagContainer().addAll(plot.getFlagContainer().getFlagMap().values());
            // Update the database
            for (final PlotFlag<?, ?> flag : existingFlags) {
                final PlotFlag<?, ?> newFlag = other.getFlagContainer().queryLocal(flag.getClass());
                if (other.getFlagContainer().queryLocal(flag.getClass()) == null) {
                    DBFunc.removeFlag(other, flag);
                } else {
                    DBFunc.setFlag(other, newFlag);
                }
            }
        }
        if (plot.isMerged()) {
            other.setMerged(plot.getMerged());
        }
        if (plot.members != null && !plot.members.isEmpty()) {
            other.members = plot.members;
            for (UUID member : plot.members) {
                DBFunc.setMember(other, member);
            }
        }
        if (plot.trusted != null && !plot.trusted.isEmpty()) {
            other.trusted = plot.trusted;
            for (UUID trusted : plot.trusted) {
                DBFunc.setTrusted(other, trusted);
            }
        }
        if (plot.denied != null && !plot.denied.isEmpty()) {
            other.denied = plot.denied;
            for (UUID denied : plot.denied) {
                DBFunc.setDenied(other, denied);
            }
        }
    }
    // copy terrain
    final ArrayDeque<CuboidRegion> regions = new ArrayDeque<>(this.plot.getRegions());
    final Runnable run = new Runnable() {

        @Override
        public void run() {
            if (regions.isEmpty()) {
                final QueueCoordinator queue = plot.getArea().getQueue();
                for (final Plot current : plot.getConnectedPlots()) {
                    destination.getManager().claimPlot(current, queue);
                }
                if (queue.size() > 0) {
                    queue.enqueue();
                }
                destination.getPlotModificationManager().setSign();
                future.complete(true);
                return;
            }
            CuboidRegion region = regions.poll();
            Location[] corners = Plot.getCorners(plot.getWorldName(), region);
            Location pos1 = corners[0];
            Location pos2 = corners[1];
            Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName());
            PlotSquared.platform().regionManager().copyRegion(pos1, pos2, newPos, actor, this);
        }
    };
    run.run();
    return future;
}
Also used : PlotFlag(com.plotsquared.core.plot.flag.PlotFlag) CuboidRegion(com.sk89q.worldedit.regions.CuboidRegion) ArrayDeque(java.util.ArrayDeque) CompletableFuture(java.util.concurrent.CompletableFuture) QueueCoordinator(com.plotsquared.core.queue.QueueCoordinator) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) UUID(java.util.UUID) Location(com.plotsquared.core.location.Location)

Example 4 with PlotFlag

use of com.plotsquared.core.plot.flag.PlotFlag in project PlotSquared by IntellectualSites.

the class SQLManager method validateAllPlots.

@SuppressWarnings({ "unchecked", "unused" })
@Override
public void validateAllPlots(Set<Plot> toValidate) {
    if (!isValid()) {
        reconnect();
    }
    LOGGER.info("All DB transactions during this session are being validated (This may take a while if corrections need to be made)");
    commit();
    while (true) {
        if (!sendBatch()) {
            break;
        }
    }
    try {
        if (this.connection.getAutoCommit()) {
            this.connection.setAutoCommit(false);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    HashMap<String, HashMap<PlotId, Plot>> database = getPlots();
    ArrayList<Plot> toCreate = new ArrayList<>();
    for (Plot plot : toValidate) {
        if (plot.temp == -1) {
            continue;
        }
        if (plot.getArea() == null) {
            LOGGER.error("CRITICAL ERROR IN VALIDATION TASK: {}", plot);
            LOGGER.error("PLOT AREA CANNOT BE NULL! SKIPPING PLOT!");
            LOGGER.info("Delete this entry from your database or set `database-purger: true` in the settings.yml");
            continue;
        }
        if (database == null) {
            LOGGER.error("CRITICAL ERROR IN VALIDATION TASK!");
            LOGGER.error("DATABASE VARIABLE CANNOT BE NULL! NOW ENDING VALIDATION!");
            break;
        }
        HashMap<PlotId, Plot> worldPlots = database.get(plot.getArea().toString());
        if (worldPlots == null) {
            toCreate.add(plot);
            continue;
        }
        Plot dataPlot = worldPlots.remove(plot.getId());
        if (dataPlot == null) {
            toCreate.add(plot);
            continue;
        }
        // owner
        if (!plot.getOwnerAbs().equals(dataPlot.getOwnerAbs())) {
            setOwner(plot, plot.getOwnerAbs());
        }
        // trusted
        if (!plot.getTrusted().equals(dataPlot.getTrusted())) {
            HashSet<UUID> toAdd = (HashSet<UUID>) plot.getTrusted().clone();
            HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getTrusted().clone();
            toRemove.removeAll(plot.getTrusted());
            toAdd.removeAll(dataPlot.getTrusted());
            if (!toRemove.isEmpty()) {
                for (UUID uuid : toRemove) {
                    removeTrusted(plot, uuid);
                }
            }
            if (!toAdd.isEmpty()) {
                for (UUID uuid : toAdd) {
                    setTrusted(plot, uuid);
                }
            }
        }
        if (!plot.getMembers().equals(dataPlot.getMembers())) {
            HashSet<UUID> toAdd = (HashSet<UUID>) plot.getMembers().clone();
            HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getMembers().clone();
            toRemove.removeAll(plot.getMembers());
            toAdd.removeAll(dataPlot.getMembers());
            if (!toRemove.isEmpty()) {
                for (UUID uuid : toRemove) {
                    removeMember(plot, uuid);
                }
            }
            if (!toAdd.isEmpty()) {
                for (UUID uuid : toAdd) {
                    setMember(plot, uuid);
                }
            }
        }
        if (!plot.getDenied().equals(dataPlot.getDenied())) {
            HashSet<UUID> toAdd = (HashSet<UUID>) plot.getDenied().clone();
            HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getDenied().clone();
            toRemove.removeAll(plot.getDenied());
            toAdd.removeAll(dataPlot.getDenied());
            if (!toRemove.isEmpty()) {
                for (UUID uuid : toRemove) {
                    removeDenied(plot, uuid);
                }
            }
            if (!toAdd.isEmpty()) {
                for (UUID uuid : toAdd) {
                    setDenied(plot, uuid);
                }
            }
        }
        boolean[] pm = plot.getMerged();
        boolean[] dm = dataPlot.getMerged();
        if (pm[0] != dm[0] || pm[1] != dm[1]) {
            setMerged(dataPlot, plot.getMerged());
        }
        Set<PlotFlag<?, ?>> pf = plot.getFlags();
        Set<PlotFlag<?, ?>> df = dataPlot.getFlags();
        if (!pf.isEmpty() && !df.isEmpty()) {
            if (pf.size() != df.size() || !StringMan.isEqual(StringMan.joinOrdered(pf, ","), StringMan.joinOrdered(df, ","))) {
            // setFlags(plot, pf);
            // TODO: Re-implement
            }
        }
    }
    for (Entry<String, HashMap<PlotId, Plot>> entry : database.entrySet()) {
        HashMap<PlotId, Plot> map = entry.getValue();
        if (!map.isEmpty()) {
            for (Entry<PlotId, Plot> entry2 : map.entrySet()) {
            // TODO implement this when sure safe"
            }
        }
    }
    commit();
}
Also used : PlotFlag(com.plotsquared.core.plot.flag.PlotFlag) SQLException(java.sql.SQLException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Plot(com.plotsquared.core.plot.Plot) ArrayList(java.util.ArrayList) PlotId(com.plotsquared.core.plot.PlotId) UUID(java.util.UUID) HashSet(java.util.HashSet)

Example 5 with PlotFlag

use of com.plotsquared.core.plot.flag.PlotFlag in project PlotSquared by IntellectualSites.

the class Music method onCommand.

@Override
public boolean onCommand(PlotPlayer<?> player, String[] args) {
    Location location = player.getLocation();
    final Plot plot = location.getPlotAbs();
    if (plot == null) {
        player.sendMessage(TranslatableCaption.of("errors.not_in_plot"));
        return false;
    }
    if (!plot.hasOwner()) {
        player.sendMessage(TranslatableCaption.of("info.plot_unowned"));
        return false;
    }
    if (!plot.isAdded(player.getUUID()) && !Permissions.hasPermission(player, Permission.PERMISSION_ADMIN_MUSIC_OTHER)) {
        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_ADMIN_MUSIC_OTHER)));
        return true;
    }
    PlotInventory inv = new PlotInventory(this.inventoryUtil, player, 2, TranslatableCaption.of("plotjukebox.jukebox_header").getComponent(player)) {

        @Override
        public boolean onClick(int index) {
            PlotItemStack item = getItem(index);
            if (item == null) {
                return true;
            }
            if (item.getType() == ItemTypes.BEDROCK) {
                PlotFlag<?, ?> plotFlag = plot.getFlagContainer().getFlag(MusicFlag.class).createFlagInstance(item.getType());
                PlotFlagRemoveEvent event = eventDispatcher.callFlagRemove(plotFlag, plot);
                if (event.getEventResult() == Result.DENY) {
                    getPlayer().sendMessage(TranslatableCaption.of("events.event_denied"), Template.of("value", "Music removal"));
                    return true;
                }
                plot.removeFlag(event.getFlag());
                getPlayer().sendMessage(TranslatableCaption.of("flag.flag_removed"), Template.of("flag", "music"), Template.of("value", "music_disc"));
            } else if (item.getName().toLowerCase(Locale.ENGLISH).contains("disc")) {
                PlotFlag<?, ?> plotFlag = plot.getFlagContainer().getFlag(MusicFlag.class).createFlagInstance(item.getType());
                PlotFlagAddEvent event = eventDispatcher.callFlagAdd(plotFlag, plot);
                if (event.getEventResult() == Result.DENY) {
                    getPlayer().sendMessage(TranslatableCaption.of("events.event_denied"), Template.of("value", "Music addition"));
                    return true;
                }
                plot.setFlag(event.getFlag());
                getPlayer().sendMessage(TranslatableCaption.of("flag.flag_added"), Template.of("flag", "music"), Template.of("value", String.valueOf(event.getFlag().getValue())));
            } else {
                getPlayer().sendMessage(TranslatableCaption.of("flag.flag_not_added"));
            }
            return false;
        }
    };
    int index = 0;
    for (final String disc : DISCS) {
        final String name = String.format("<gold>%s</gold>", disc);
        final String[] lore = { TranslatableCaption.of("plotjukebox.click_to_play").getComponent(player) };
        ItemType type = ItemTypes.get(disc);
        if (type == null) {
            continue;
        }
        final PlotItemStack item = new PlotItemStack(type, 1, name, lore);
        if (inv.setItemChecked(index, item)) {
            index++;
        }
    }
    // Always add the cancel button
    // if (player.getMeta("music") != null) {
    String name = TranslatableCaption.of("plotjukebox.cancel_music").getComponent(player);
    String[] lore = { TranslatableCaption.of("plotjukebox.reset_music").getComponent(player) };
    inv.setItem(index, new PlotItemStack("bedrock", 1, name, lore));
    // }
    inv.openInventory();
    return true;
}
Also used : PlotFlag(com.plotsquared.core.plot.flag.PlotFlag) Plot(com.plotsquared.core.plot.Plot) ItemType(com.sk89q.worldedit.world.item.ItemType) PlotItemStack(com.plotsquared.core.plot.PlotItemStack) PlotInventory(com.plotsquared.core.plot.PlotInventory) PlotFlagAddEvent(com.plotsquared.core.events.PlotFlagAddEvent) PlotFlagRemoveEvent(com.plotsquared.core.events.PlotFlagRemoveEvent) MusicFlag(com.plotsquared.core.plot.flag.implementations.MusicFlag) Location(com.plotsquared.core.location.Location)

Aggregations

PlotFlag (com.plotsquared.core.plot.flag.PlotFlag)6 Location (com.plotsquared.core.location.Location)4 Plot (com.plotsquared.core.plot.Plot)4 TranslatableCaption (com.plotsquared.core.configuration.caption.TranslatableCaption)3 PlotFlagRemoveEvent (com.plotsquared.core.events.PlotFlagRemoveEvent)3 UUID (java.util.UUID)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 Settings (com.plotsquared.core.configuration.Settings)2 Caption (com.plotsquared.core.configuration.caption.Caption)2 StaticCaption (com.plotsquared.core.configuration.caption.StaticCaption)2 Result (com.plotsquared.core.events.Result)2 PlotPlayer (com.plotsquared.core.player.PlotPlayer)2 MusicFlag (com.plotsquared.core.plot.flag.implementations.MusicFlag)2 ItemType (com.sk89q.worldedit.world.item.ItemType)2 HashMap (java.util.HashMap)2 Template (net.kyori.adventure.text.minimessage.Template)2 Inject (com.google.inject.Inject)1 PlotSquared (com.plotsquared.core.PlotSquared)1 BackupManager (com.plotsquared.core.backup.BackupManager)1 DBFunc (com.plotsquared.core.database.DBFunc)1