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.PlotSquared;
023import com.plotsquared.core.configuration.caption.StaticCaption;
024import com.plotsquared.core.configuration.caption.TranslatableCaption;
025import com.plotsquared.core.player.PlotPlayer;
026import com.plotsquared.core.plot.world.PlotAreaManager;
027import com.plotsquared.core.util.StringMan;
028import com.plotsquared.core.util.WorldUtil;
029import com.plotsquared.core.util.entity.EntityCategories;
030import com.plotsquared.core.util.entity.EntityCategory;
031import com.plotsquared.core.util.query.PlotQuery;
032import com.plotsquared.core.util.task.TaskManager;
033import com.plotsquared.core.uuid.UUIDMapping;
034import com.sk89q.worldedit.world.entity.EntityType;
035import net.kyori.adventure.text.Component;
036import net.kyori.adventure.text.TextComponent;
037import net.kyori.adventure.text.minimessage.Template;
038import org.checkerframework.checker.nullness.qual.NonNull;
039
040import java.util.Collection;
041import java.util.Comparator;
042import java.util.Locale;
043import java.util.Map;
044import java.util.Set;
045import java.util.stream.Collectors;
046import java.util.stream.Stream;
047
048@CommandDeclaration(command = "debug",
049        category = CommandCategory.DEBUG,
050        usage = "/plot debug",
051        permission = "plots.admin")
052public class Debug extends SubCommand {
053
054    private final PlotAreaManager plotAreaManager;
055    private final WorldUtil worldUtil;
056
057    @Inject
058    public Debug(
059            final @NonNull PlotAreaManager plotAreaManager,
060            final @NonNull WorldUtil worldUtil
061    ) {
062        this.plotAreaManager = plotAreaManager;
063        this.worldUtil = worldUtil;
064    }
065
066    @Override
067    public boolean onCommand(PlotPlayer<?> player, String[] args) {
068        if (args.length == 0) {
069            player.sendMessage(
070                    TranslatableCaption.of("commandconfig.command_syntax"),
071                    Template.of("value", "/plot debug <loadedchunks | player | debug-players | entitytypes | msg>")
072            );
073        }
074        if (args.length > 0) {
075            if ("player".equalsIgnoreCase(args[0])) {
076                for (Map.Entry<String, Object> meta : player.getMeta().entrySet()) {
077                    player.sendMessage(StaticCaption.of("Key: " + meta.getKey() + " Value: " + meta
078                            .getValue()
079                            .toString() + " , "));
080                }
081                return true;
082            }
083        }
084        if (args.length > 0 && "loadedchunks".equalsIgnoreCase(args[0])) {
085            final long start = System.currentTimeMillis();
086            player.sendMessage(TranslatableCaption.of("debug.fetching_loaded_chunks"));
087            TaskManager.runTaskAsync(() -> player.sendMessage(StaticCaption
088                    .of("Loaded chunks: " + this.worldUtil
089                            .getChunkChunks(player.getLocation().getWorldName())
090                            .size() + " (" + (System.currentTimeMillis()
091                            - start) + "ms) using thread: " + Thread.currentThread().getName())));
092            return true;
093        }
094        if (args.length > 0 && "uuids".equalsIgnoreCase(args[0])) {
095            final Collection<UUIDMapping> mappings = PlotSquared.get().getImpromptuUUIDPipeline().getAllImmediately();
096            player.sendMessage(
097                    TranslatableCaption.of("debug.cached_uuids"),
098                    Template.of("value", String.valueOf(mappings.size()))
099            );
100            return true;
101        }
102        if (args.length > 0 && "debug-players".equalsIgnoreCase(args[0])) {
103            player.sendMessage(TranslatableCaption.of("debug.player_in_debugmode"));
104            for (final PlotPlayer<?> pp : PlotPlayer.getDebugModePlayers()) {
105                player.sendMessage(
106                        TranslatableCaption.of("debug.player_in_debugmode_list"),
107                        Template.of("value", pp.getName())
108                );
109            }
110            return true;
111        }
112        if (args.length > 0 && "entitytypes".equalsIgnoreCase(args[0])) {
113            EntityCategories.init();
114            player.sendMessage(TranslatableCaption.of("debug.entity_categories"));
115            EntityCategory.REGISTRY.forEach(category -> {
116                final StringBuilder builder =
117                        new StringBuilder("§7- §6").append(category.getId()).append("§7: §6");
118                for (final EntityType entityType : category.getAll()) {
119                    builder.append(entityType.getId()).append(" ");
120                }
121                player.sendMessage(StaticCaption.of("<prefix>" + builder));
122            });
123            EntityType.REGISTRY.values().stream().sorted(Comparator.comparing(EntityType::getId))
124                    .forEach(entityType -> {
125                        long categoryCount = EntityCategory.REGISTRY.values().stream()
126                                .filter(category -> category.contains(entityType)).count();
127                        if (categoryCount > 0) {
128                            return;
129                        }
130                        player.sendMessage(StaticCaption.of("<prefix>" + entityType.getName() + " is in "
131                                + categoryCount + " categories"));
132                    });
133            return true;
134        }
135        Set<TranslatableCaption> captions = PlotSquared
136                .get()
137                .getCaptionMap(TranslatableCaption.DEFAULT_NAMESPACE)
138                .getCaptions();
139        TextComponent.Builder information = Component.text();
140        Component header = MINI_MESSAGE.parse(TranslatableCaption.of("debug.debug_header").getComponent(player) + "\n");
141        String line = TranslatableCaption.of("debug.debug_line").getComponent(player) + "\n";
142        String section = TranslatableCaption.of("debug.debug_section").getComponent(player) + "\n";
143        information.append(header);
144        information.append(MINI_MESSAGE.parse(section, Template.of("val", "PlotArea")));
145        information.append(MINI_MESSAGE
146                .parse(
147                        line,
148                        Template.of("var", "Plot Worlds"),
149                        Template.of("val", StringMan.join(this.plotAreaManager.getAllPlotAreas(), ", "))
150                ));
151        information.append(
152                MINI_MESSAGE.parse(
153                        line,
154                        Template.of("var", "Owned Plots"),
155                        Template.of("val", String.valueOf(PlotQuery.newQuery().allPlots().count()))
156                ));
157        information.append(MINI_MESSAGE.parse(section, Template.of("val", "Messages")));
158        information.append(MINI_MESSAGE.parse(
159                line,
160                Template.of("var", "Total Messages"),
161                Template.of("val", String.valueOf(captions.size()))
162        ));
163        player.sendMessage(StaticCaption.of(MINI_MESSAGE.serialize(information.build())));
164        return true;
165    }
166
167    @Override
168    public Collection<Command> tab(final PlotPlayer<?> player, String[] args, boolean space) {
169        return Stream.of("loadedchunks", "debug-players", "entitytypes")
170                .filter(value -> value.startsWith(args[0].toLowerCase(Locale.ENGLISH)))
171                .map(value -> new Command(null, false, value, "plots.admin", RequiredType.NONE, null) {
172                }).collect(Collectors.toList());
173    }
174
175}