001/*
002 * Copyright (c) 2016-2017 Daniel Ennis (Aikar) - MIT License
003 *
004 *  Permission is hereby granted, free of charge, to any person obtaining
005 *  a copy of this software and associated documentation files (the
006 *  "Software"), to deal in the Software without restriction, including
007 *  without limitation the rights to use, copy, modify, merge, publish,
008 *  distribute, sublicense, and/or sell copies of the Software, and to
009 *  permit persons to whom the Software is furnished to do so, subject to
010 *  the following conditions:
011 *
012 *  The above copyright notice and this permission notice shall be
013 *  included in all copies or substantial portions of the Software.
014 *
015 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
016 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
017 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
018 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
019 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
020 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
021 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
022 */
023
024package co.aikar.commands;
025
026import co.aikar.commands.apachecommonslang.ApacheCommonsExceptionUtil;
027import co.aikar.timings.Timing;
028import co.aikar.timings.Timings;
029import org.slf4j.Logger;
030import org.spongepowered.api.Sponge;
031import org.spongepowered.api.command.CommandSource;
032import org.spongepowered.api.plugin.PluginContainer;
033import org.spongepowered.api.text.format.TextColor;
034import org.spongepowered.api.text.format.TextColors;
035
036import java.lang.reflect.Method;
037import java.lang.reflect.Parameter;
038import java.util.HashMap;
039import java.util.List;
040import java.util.Map;
041
042@SuppressWarnings("WeakerAccess")
043public class SpongeCommandManager extends CommandManager<
044        CommandSource,
045        SpongeCommandIssuer,
046        TextColor,
047        SpongeMessageFormatter,
048        SpongeCommandExecutionContext,
049        SpongeConditionContext
050    > {
051
052    protected final PluginContainer plugin;
053    protected Map<String, SpongeRootCommand> registeredCommands = new HashMap<>();
054    protected SpongeCommandContexts contexts;
055    protected SpongeCommandCompletions completions;
056    private Timing commandTiming;
057    protected SpongeLocales locales;
058
059    public SpongeCommandManager(PluginContainer plugin) {
060        this.plugin = plugin;
061        String pluginName = "acf-" + plugin.getName();
062        getLocales().addMessageBundles("acf-minecraft", pluginName, pluginName.toLowerCase());
063        this.commandTiming = Timings.of(plugin, "Commands");
064
065        this.formatters.put(MessageType.ERROR, defaultFormatter = new SpongeMessageFormatter(TextColors.RED, TextColors.YELLOW, TextColors.RED));
066        this.formatters.put(MessageType.SYNTAX, new SpongeMessageFormatter(TextColors.YELLOW, TextColors.GREEN, TextColors.WHITE));
067        this.formatters.put(MessageType.INFO, new SpongeMessageFormatter(TextColors.BLUE, TextColors.DARK_GREEN, TextColors.GREEN));
068        this.formatters.put(MessageType.HELP, new SpongeMessageFormatter(TextColors.AQUA, TextColors.GREEN, TextColors.YELLOW));
069        getLocales(); // auto load locales
070    }
071
072    public PluginContainer getPlugin() {
073        return plugin;
074    }
075
076    @Override
077    public boolean isCommandIssuer(Class<?> type) {
078        return CommandSource.class.isAssignableFrom(type);
079    }
080
081    @Override
082    public synchronized CommandContexts<SpongeCommandExecutionContext> getCommandContexts() {
083        if (this.contexts == null) {
084            this.contexts = new SpongeCommandContexts(this);
085        }
086        return contexts;
087    }
088
089    @Override
090    public synchronized CommandCompletions<SpongeCommandCompletionContext> getCommandCompletions() {
091        if (this.completions == null) {
092            this.completions = new SpongeCommandCompletions(this);
093        }
094        return completions;
095    }
096
097    @Override
098    public SpongeLocales getLocales() {
099        if (this.locales == null) {
100            this.locales = new SpongeLocales(this);
101            this.locales.loadLanguages();
102        }
103        return locales;
104    }
105
106    @Override
107    public boolean hasRegisteredCommands() {
108        return !registeredCommands.isEmpty();
109    }
110
111    @Override
112    public void registerCommand(BaseCommand command) {
113        command.onRegister(this);
114
115        for (Map.Entry<String, RootCommand> entry : command.registeredCommands.entrySet()) {
116            String commandName = entry.getKey().toLowerCase();
117            SpongeRootCommand spongeCommand = (SpongeRootCommand) entry.getValue();
118            if (!spongeCommand.isRegistered) {
119                Sponge.getCommandManager().register(this.plugin, spongeCommand, commandName);
120            }
121            spongeCommand.isRegistered = true;
122            registeredCommands.put(commandName, spongeCommand);
123        }
124    }
125
126    public Timing createTiming(final String name) {
127        return Timings.of(this.plugin, name, this.commandTiming);
128    }
129
130    @Override
131    public RootCommand createRootCommand(String cmd) {
132        return new SpongeRootCommand(this, cmd);
133    }
134
135    @Override
136    public SpongeCommandIssuer getCommandIssuer(Object issuer) {
137        if (!(issuer instanceof CommandSource)) {
138            throw new IllegalArgumentException(issuer.getClass().getName() + " is not a Command Issuer.");
139        }
140        return new SpongeCommandIssuer(this, (CommandSource) issuer);
141    }
142
143    @Override
144    public SpongeCommandExecutionContext createCommandContext(RegisteredCommand command, Parameter parameter, CommandIssuer sender, List<String> args, int i, Map<String, Object> passedArgs) {
145        return new SpongeCommandExecutionContext(command, parameter, (SpongeCommandIssuer) sender, args, i, passedArgs);
146    }
147
148    @Override
149    public CommandCompletionContext createCompletionContext(RegisteredCommand command, CommandIssuer sender, String input, String config, String[] args) {
150        return new SpongeCommandCompletionContext(command, (SpongeCommandIssuer) sender, input, config, args);
151    }
152
153    @Override
154    public RegisteredCommand createRegisteredCommand(BaseCommand command, String cmdName, Method method, String prefSubCommand) {
155        return new SpongeRegisteredCommand(command, cmdName, method, prefSubCommand);
156    }
157
158    @Override
159    public void log(final LogLevel level, final String message, final Throwable throwable) {
160        Logger logger = this.plugin.getLogger();
161        switch(level) {
162            case INFO:
163                logger.info(LogLevel.LOG_PREFIX + message);
164                if (throwable != null) {
165                    for (String line : ACFPatterns.NEWLINE.split(ApacheCommonsExceptionUtil.getFullStackTrace(throwable))) {
166                        logger.info(LogLevel.LOG_PREFIX + line);
167                    }
168                }
169                return;
170            case ERROR:
171                logger.error(LogLevel.LOG_PREFIX + message);
172                if (throwable != null) {
173                    for (String line : ACFPatterns.NEWLINE.split(ApacheCommonsExceptionUtil.getFullStackTrace(throwable))) {
174                        logger.error(LogLevel.LOG_PREFIX + line);
175                    }
176                }
177        }
178    }
179
180    @Override
181    CommandOperationContext createCommandOperationContext(BaseCommand command, CommandIssuer issuer, String commandLabel, String[] args, boolean isAsync) {
182        return new SpongeCommandOperationContext(
183                this,
184                issuer,
185                command,
186                commandLabel,
187                args,
188                isAsync
189        );
190    }
191
192    @Override
193    public SpongeConditionContext createConditionContext(CommandIssuer issuer, String config) {
194        return new SpongeConditionContext((SpongeCommandIssuer) issuer, config);
195    }
196
197}