001//
002// MIT License
003//
004// Copyright (c) 2021 Alexander Söderberg & Contributors
005//
006// Permission is hereby granted, free of charge, to any person obtaining a copy
007// of this software and associated documentation files (the "Software"), to deal
008// in the Software without restriction, including without limitation the rights
009// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
010// copies of the Software, and to permit persons to whom the Software is
011// furnished to do so, subject to the following conditions:
012//
013// The above copyright notice and this permission notice shall be included in all
014// copies or substantial portions of the Software.
015//
016// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
017// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
018// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
019// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
020// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
021// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
022// SOFTWARE.
023//
024package cloud.commandframework.bungee;
025
026import cloud.commandframework.arguments.CommandArgument;
027import cloud.commandframework.arguments.StaticArgument;
028import cloud.commandframework.exceptions.ArgumentParseException;
029import cloud.commandframework.exceptions.CommandExecutionException;
030import cloud.commandframework.exceptions.InvalidCommandSenderException;
031import cloud.commandframework.exceptions.InvalidSyntaxException;
032import cloud.commandframework.exceptions.NoPermissionException;
033import cloud.commandframework.exceptions.NoSuchCommandException;
034import net.md_5.bungee.api.ChatColor;
035import net.md_5.bungee.api.CommandSender;
036import net.md_5.bungee.api.chat.ComponentBuilder;
037import net.md_5.bungee.api.plugin.Command;
038import net.md_5.bungee.api.plugin.TabExecutor;
039import org.checkerframework.checker.nullness.qual.NonNull;
040
041import java.util.concurrent.CompletionException;
042import java.util.logging.Level;
043
044public final class BungeeCommand<C> extends Command implements TabExecutor {
045
046    private static final String MESSAGE_INTERNAL_ERROR = "An internal error occurred while attempting to perform this command.";
047    private static final String MESSAGE_NO_PERMS =
048            "I'm sorry, but you do not have permission to perform this command. "
049                    + "Please contact the server administrators if you believe that this is in error.";
050    private static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command. Type \"/help\" for help.";
051
052    private final BungeeCommandManager<C> manager;
053    private final CommandArgument<C, ?> command;
054
055    @SuppressWarnings("unchecked")
056    BungeeCommand(
057            final cloud.commandframework.@NonNull Command<C> cloudCommand,
058            final @NonNull CommandArgument<C, ?> command,
059            final @NonNull BungeeCommandManager<C> manager
060    ) {
061        super(
062                command.getName(),
063                cloudCommand.getCommandPermission().toString(),
064                ((StaticArgument<C>) command).getAlternativeAliases().toArray(new String[0])
065        );
066        this.command = command;
067        this.manager = manager;
068    }
069
070    @Override
071    public void execute(final CommandSender commandSender, final String[] strings) {
072        /* Join input */
073        final StringBuilder builder = new StringBuilder(this.command.getName());
074        for (final String string : strings) {
075            builder.append(" ").append(string);
076        }
077        final C sender = this.manager.getCommandSenderMapper().apply(commandSender);
078        this.manager.executeCommand(
079                sender,
080                builder.toString()
081        )
082                .whenComplete((commandResult, throwable) -> {
083                    if (throwable != null) {
084                        if (throwable instanceof CompletionException) {
085                            throwable = throwable.getCause();
086                        }
087                        final Throwable finalThrowable = throwable;
088                        if (throwable instanceof InvalidSyntaxException) {
089                            this.manager.handleException(sender,
090                                    InvalidSyntaxException.class,
091                                    (InvalidSyntaxException) throwable, (c, e) ->
092                                            commandSender.sendMessage(
093                                                    new ComponentBuilder(
094                                                            "Invalid Command Syntax. Correct command syntax is: ")
095                                                            .color(ChatColor.RED)
096                                                            .append("/")
097                                                            .color(ChatColor.GRAY)
098                                                            .append(((InvalidSyntaxException) finalThrowable)
099                                                                    .getCorrectSyntax())
100                                                            .color(ChatColor.GRAY)
101                                                            .create()
102                                            )
103                            );
104                        } else if (throwable instanceof InvalidCommandSenderException) {
105                            final Throwable finalThrowable1 = throwable;
106                            this.manager.handleException(sender,
107                                    InvalidCommandSenderException.class,
108                                    (InvalidCommandSenderException) throwable, (c, e) ->
109                                            commandSender.sendMessage(new ComponentBuilder(
110                                                    finalThrowable1.getMessage())
111                                                    .color(ChatColor.RED)
112                                                    .create())
113                            );
114                        } else if (throwable instanceof NoPermissionException) {
115                            this.manager.handleException(sender,
116                                    NoPermissionException.class,
117                                    (NoPermissionException) throwable, (c, e) ->
118                                            commandSender.sendMessage(new ComponentBuilder(
119                                                    MESSAGE_NO_PERMS)
120                                                    .color(ChatColor.WHITE)
121                                                    .create())
122                            );
123                        } else if (throwable instanceof NoSuchCommandException) {
124                            this.manager.handleException(sender,
125                                    NoSuchCommandException.class,
126                                    (NoSuchCommandException) throwable, (c, e) ->
127                                            commandSender.sendMessage(new ComponentBuilder(
128                                                    MESSAGE_UNKNOWN_COMMAND)
129                                                    .color(ChatColor.WHITE)
130                                                    .create())
131                            );
132                        } else if (throwable instanceof ArgumentParseException) {
133                            this.manager.handleException(sender,
134                                    ArgumentParseException.class,
135                                    (ArgumentParseException) throwable, (c, e) ->
136                                            commandSender.sendMessage(new ComponentBuilder(
137                                                    "Invalid Command Argument: ")
138                                                    .color(ChatColor.GRAY)
139                                                    .append(finalThrowable
140                                                            .getCause()
141                                                            .getMessage())
142                                                    .create())
143                            );
144                        } else if (throwable instanceof CommandExecutionException) {
145                            this.manager.handleException(sender,
146                                    CommandExecutionException.class,
147                                    (CommandExecutionException) throwable, (c, e) -> {
148                                        commandSender.sendMessage(new ComponentBuilder(MESSAGE_INTERNAL_ERROR)
149                                                .color(ChatColor.RED)
150                                                .create());
151                                        this.manager.getOwningPlugin().getLogger().log(
152                                                Level.SEVERE,
153                                                "Exception executing command handler",
154                                                finalThrowable.getCause()
155                                        );
156                                    }
157                            );
158                        } else {
159                            commandSender.sendMessage(new ComponentBuilder(MESSAGE_INTERNAL_ERROR).color(ChatColor.RED).create());
160                            this.manager.getOwningPlugin().getLogger().log(
161                                    Level.SEVERE,
162                                    "An unhandled exception was thrown during command execution",
163                                    throwable
164                            );
165                        }
166                    }
167                });
168    }
169
170    @Override
171    public Iterable<String> onTabComplete(
172            final CommandSender sender,
173            final String[] args
174    ) {
175        final StringBuilder builder = new StringBuilder(this.command.getName());
176        for (final String string : args) {
177            builder.append(" ").append(string);
178        }
179        return this.manager.suggest(
180                this.manager.getCommandSenderMapper().apply(sender),
181                builder.toString()
182        );
183    }
184
185}