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        //TODO more default dependencies for sponge
072        registerDependency(plugin.getClass(), plugin);
073    }
074
075    public PluginContainer getPlugin() {
076        return plugin;
077    }
078
079    @Override
080    public boolean isCommandIssuer(Class<?> type) {
081        return CommandSource.class.isAssignableFrom(type);
082    }
083
084    @Override
085    public synchronized CommandContexts<SpongeCommandExecutionContext> getCommandContexts() {
086        if (this.contexts == null) {
087            this.contexts = new SpongeCommandContexts(this);
088        }
089        return contexts;
090    }
091
092    @Override
093    public synchronized CommandCompletions<SpongeCommandCompletionContext> getCommandCompletions() {
094        if (this.completions == null) {
095            this.completions = new SpongeCommandCompletions(this);
096        }
097        return completions;
098    }
099
100    @Override
101    public SpongeLocales getLocales() {
102        if (this.locales == null) {
103            this.locales = new SpongeLocales(this);
104            this.locales.loadLanguages();
105        }
106        return locales;
107    }
108
109    @Override
110    public boolean hasRegisteredCommands() {
111        return !registeredCommands.isEmpty();
112    }
113
114    @Override
115    public void registerCommand(BaseCommand command) {
116        command.onRegister(this);
117
118        for (Map.Entry<String, RootCommand> entry : command.registeredCommands.entrySet()) {
119            String commandName = entry.getKey().toLowerCase();
120            SpongeRootCommand spongeCommand = (SpongeRootCommand) entry.getValue();
121            if (!spongeCommand.isRegistered) {
122                Sponge.getCommandManager().register(this.plugin, spongeCommand, commandName);
123            }
124            spongeCommand.isRegistered = true;
125            registeredCommands.put(commandName, spongeCommand);
126        }
127    }
128
129    public Timing createTiming(final String name) {
130        return Timings.of(this.plugin, name, this.commandTiming);
131    }
132
133    @Override
134    public RootCommand createRootCommand(String cmd) {
135        return new SpongeRootCommand(this, cmd);
136    }
137
138    @Override
139    public SpongeCommandIssuer getCommandIssuer(Object issuer) {
140        if (!(issuer instanceof CommandSource)) {
141            throw new IllegalArgumentException(issuer.getClass().getName() + " is not a Command Issuer.");
142        }
143        return new SpongeCommandIssuer(this, (CommandSource) issuer);
144    }
145
146    @Override
147    public SpongeCommandExecutionContext createCommandContext(RegisteredCommand command, Parameter parameter, CommandIssuer sender, List<String> args, int i, Map<String, Object> passedArgs) {
148        return new SpongeCommandExecutionContext(command, parameter, (SpongeCommandIssuer) sender, args, i, passedArgs);
149    }
150
151    @Override
152    public CommandCompletionContext createCompletionContext(RegisteredCommand command, CommandIssuer sender, String input, String config, String[] args) {
153        return new SpongeCommandCompletionContext(command, (SpongeCommandIssuer) sender, input, config, args);
154    }
155
156    @Override
157    public RegisteredCommand createRegisteredCommand(BaseCommand command, String cmdName, Method method, String prefSubCommand) {
158        return new SpongeRegisteredCommand(command, cmdName, method, prefSubCommand);
159    }
160
161    @Override
162    public void log(final LogLevel level, final String message, final Throwable throwable) {
163        Logger logger = this.plugin.getLogger();
164        switch(level) {
165            case INFO:
166                logger.info(LogLevel.LOG_PREFIX + message);
167                if (throwable != null) {
168                    for (String line : ACFPatterns.NEWLINE.split(ApacheCommonsExceptionUtil.getFullStackTrace(throwable))) {
169                        logger.info(LogLevel.LOG_PREFIX + line);
170                    }
171                }
172                return;
173            case ERROR:
174                logger.error(LogLevel.LOG_PREFIX + message);
175                if (throwable != null) {
176                    for (String line : ACFPatterns.NEWLINE.split(ApacheCommonsExceptionUtil.getFullStackTrace(throwable))) {
177                        logger.error(LogLevel.LOG_PREFIX + line);
178                    }
179                }
180        }
181    }
182
183    @Override
184    CommandOperationContext createCommandOperationContext(BaseCommand command, CommandIssuer issuer, String commandLabel, String[] args, boolean isAsync) {
185        return new SpongeCommandOperationContext(
186                this,
187                issuer,
188                command,
189                commandLabel,
190                args,
191                isAsync
192        );
193    }
194
195    @Override
196    public SpongeConditionContext createConditionContext(CommandIssuer issuer, String config) {
197        return new SpongeConditionContext((SpongeCommandIssuer) issuer, config);
198    }
199
200}