001/*
002 * PlotSquared, a land and world management plugin for Minecraft.
003 * Copyright (C) IntellectualSites <https://intellectualsites.com>
004 * Copyright (C) IntellectualSites team and contributors
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
018 */
019package com.plotsquared.core.command;
020
021import com.google.inject.Inject;
022import com.plotsquared.core.configuration.Settings;
023import com.plotsquared.core.configuration.caption.TranslatableCaption;
024import com.plotsquared.core.database.DBFunc;
025import com.plotsquared.core.permissions.Permission;
026import com.plotsquared.core.player.PlotPlayer;
027import com.plotsquared.core.plot.Plot;
028import com.plotsquared.core.util.EventDispatcher;
029import com.plotsquared.core.util.PlayerManager;
030import com.plotsquared.core.util.TabCompletions;
031import com.plotsquared.core.util.task.RunnableVal2;
032import com.plotsquared.core.util.task.RunnableVal3;
033import net.kyori.adventure.text.Component;
034import net.kyori.adventure.text.minimessage.tag.Tag;
035import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
036import org.checkerframework.checker.nullness.qual.NonNull;
037
038import java.util.Collection;
039import java.util.Collections;
040import java.util.Iterator;
041import java.util.UUID;
042import java.util.concurrent.CompletableFuture;
043import java.util.concurrent.TimeoutException;
044
045@CommandDeclaration(command = "trust",
046        aliases = {"t"},
047        requiredType = RequiredType.PLAYER,
048        usage = "/plot trust <player | *>",
049        category = CommandCategory.SETTINGS)
050public class Trust extends Command {
051
052    private final EventDispatcher eventDispatcher;
053
054    @Inject
055    public Trust(final @NonNull EventDispatcher eventDispatcher) {
056        super(MainCommand.getInstance(), true);
057        this.eventDispatcher = eventDispatcher;
058    }
059
060    @Override
061    public CompletableFuture<Boolean> execute(
062            final PlotPlayer<?> player, String[] args,
063            RunnableVal3<Command, Runnable, Runnable> confirm,
064            RunnableVal2<Command, CommandResult> whenDone
065    ) throws CommandException {
066        final Plot currentPlot = player.getCurrentPlot();
067        if (currentPlot == null) {
068            throw new CommandException(TranslatableCaption.of("errors.not_in_plot"));
069        }
070        checkTrue(currentPlot.hasOwner(), TranslatableCaption.of("info.plot_unowned"));
071        checkTrue(
072                currentPlot.isOwner(player.getUUID()) || player.hasPermission(Permission.PERMISSION_ADMIN_COMMAND_TRUST),
073                TranslatableCaption.of("permission.no_plot_perms")
074        );
075
076        checkTrue(args.length == 1, TranslatableCaption.of("commandconfig.command_syntax"),
077                TagResolver.resolver("value", Tag.inserting(Component.text(getUsage())))
078        );
079
080        final CompletableFuture<Boolean> future = new CompletableFuture<>();
081        PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
082            if (throwable != null) {
083                if (throwable instanceof TimeoutException) {
084                    player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
085                } else {
086                    player.sendMessage(
087                            TranslatableCaption.of("errors.invalid_player"),
088                            TagResolver.resolver("value", Tag.inserting(Component.text(args[0])))
089                    );
090                }
091                future.completeExceptionally(throwable);
092                return;
093            } else {
094                checkTrue(!uuids.isEmpty(), TranslatableCaption.of("errors.invalid_player"),
095                        TagResolver.resolver("value", Tag.inserting(Component.text(args[0])))
096                );
097
098                Iterator<UUID> iterator = uuids.iterator();
099                int size = currentPlot.getTrusted().size() + currentPlot.getMembers().size();
100                while (iterator.hasNext()) {
101                    UUID uuid = iterator.next();
102                    if (uuid == DBFunc.EVERYONE && !(
103                            player.hasPermission(Permission.PERMISSION_TRUST_EVERYONE) || player.hasPermission(Permission.PERMISSION_ADMIN_COMMAND_TRUST))) {
104                        player.sendMessage(
105                                TranslatableCaption.of("errors.invalid_player"),
106                                TagResolver.resolver(
107                                        "value",
108                                        Tag.inserting(PlayerManager.resolveName(uuid).toComponent(player))
109                                )
110                        );
111                        iterator.remove();
112                        continue;
113                    }
114                    if (currentPlot.isOwner(uuid)) {
115                        player.sendMessage(
116                                TranslatableCaption.of("member.already_added"),
117                                TagResolver.resolver(
118                                        "value",
119                                        Tag.inserting(PlayerManager.resolveName(uuid).toComponent(player))
120                                )
121                        );
122                        iterator.remove();
123                        continue;
124                    }
125                    if (currentPlot.getTrusted().contains(uuid)) {
126                        player.sendMessage(
127                                TranslatableCaption.of("member.already_added"),
128                                TagResolver.resolver(
129                                        "value",
130                                        Tag.inserting(PlayerManager.resolveName(uuid).toComponent(player))
131                                )
132                        );
133                        iterator.remove();
134                        continue;
135                    }
136                    size += currentPlot.getMembers().contains(uuid) ? 0 : 1;
137                }
138                checkTrue(!uuids.isEmpty(), null);
139                int localTrustSize = currentPlot.getTrusted().size();
140                int maxTrustSize = player.hasPermissionRange(Permission.PERMISSION_TRUST, Settings.Limit.MAX_PLOTS);
141                if (localTrustSize >= maxTrustSize) {
142                    player.sendMessage(
143                            TranslatableCaption.of("members.plot_max_members_trusted"),
144                            TagResolver.resolver("amount", Tag.inserting(Component.text(localTrustSize)))
145                    );
146                    return;
147                }
148                // Success
149                confirm.run(this, () -> {
150                    for (UUID uuid : uuids) {
151                        if (uuid != DBFunc.EVERYONE) {
152                            if (!currentPlot.removeMember(uuid)) {
153                                if (currentPlot.getDenied().contains(uuid)) {
154                                    currentPlot.removeDenied(uuid);
155                                }
156                            }
157                        }
158                        currentPlot.addTrusted(uuid);
159                        this.eventDispatcher.callTrusted(player, currentPlot, uuid, true);
160                        player.sendMessage(TranslatableCaption.of("trusted.trusted_added"));
161                    }
162                }, null);
163            }
164            future.complete(true);
165        });
166        return CompletableFuture.completedFuture(true);
167    }
168
169    @Override
170    public Collection<Command> tab(final PlotPlayer<?> player, final String[] args, final boolean space) {
171        return TabCompletions.completePlayers(player, String.join(",", args).trim(), Collections.emptyList());
172    }
173
174}