summaryrefslogtreecommitdiff
path: root/dicore3/command/src/main/java/io/dico/dicore/command/registration/CommandMap.java
blob: 2008b2921855c948129e2bef324c6ec17912b56c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package io.dico.dicore.command.registration;

import io.dico.dicore.Reflection;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.plugin.SimplePluginManager;

import java.util.*;

/**
 * Provides access to bukkit's {@code Map<String, org.bukkit.command.Command>} command map.
 */
@SuppressWarnings("ConstantConditions")
public class CommandMap {
    private static final Map<String, Command> commandMap = findCommandMap();

    private CommandMap() {

    }

    public static Map<String, Command> getCommandMap() {
        return Objects.requireNonNull(commandMap);
    }

    public static boolean isAvailable() {
        return commandMap != null;
    }

    public static Command get(String key) {
        return commandMap.get(key);
    }

    public static void put(String key, Command command) {
        commandMap.put(key, command);
    }

    public static Collection<String> replace(Command command, Command replacement) {
        List<String> result = new ArrayList<>();
        for (Map.Entry<String, Command> entry : commandMap.entrySet()) {
            if (entry.getValue() == command) {
                entry.setValue(replacement);
                result.add(entry.getKey());
            }
        }
        return result;
    }

    private static Map<String, Command> findCommandMap() {
        try {
            return Reflection.getFieldValue(SimpleCommandMap.class, "knownCommands",
                    Reflection.getFieldValue(SimplePluginManager.class, "commandMap", Bukkit.getPluginManager()));
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

}