From 77884f0a11882b61264d7d672b9466a456968ab0 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 18 Nov 2023 14:51:09 -0800 Subject: [PATCH] Update to BentoBox 2.0.0 API --- .../world/bentobox/level/LevelsManager.java | 2 +- .../bentobox/level/panels/DetailsPanel.java | 1421 ++++++++--------- .../bentobox/level/LevelsManagerTest.java | 536 ++++--- 3 files changed, 924 insertions(+), 1035 deletions(-) diff --git a/src/main/java/world/bentobox/level/LevelsManager.java b/src/main/java/world/bentobox/level/LevelsManager.java index 087ab0d..fa8083d 100644 --- a/src/main/java/world/bentobox/level/LevelsManager.java +++ b/src/main/java/world/bentobox/level/LevelsManager.java @@ -356,7 +356,7 @@ public Map getTopTenLists() { public int getRank(@NonNull World world, UUID uuid) { createAndCleanRankings(world); Stream> stream = topTenLists.get(world).getTopTen().entrySet().stream() - .filter(e -> addon.getIslands().isOwner(world, e.getKey())).filter(l -> l.getValue() > 0) + .filter(e -> addon.getIslands().hasIsland(world, e.getKey())).filter(l -> l.getValue() > 0) .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())); return (int) (stream.takeWhile(x -> !x.getKey().equals(uuid)).map(Map.Entry::getKey).count() + 1); } diff --git a/src/main/java/world/bentobox/level/panels/DetailsPanel.java b/src/main/java/world/bentobox/level/panels/DetailsPanel.java index 395e5ed..fad4988 100644 --- a/src/main/java/world/bentobox/level/panels/DetailsPanel.java +++ b/src/main/java/world/bentobox/level/panels/DetailsPanel.java @@ -1,6 +1,5 @@ package world.bentobox.level.panels; - import java.io.File; import java.util.ArrayList; import java.util.Comparator; @@ -30,775 +29,659 @@ import world.bentobox.level.objects.IslandLevels; import world.bentobox.level.util.Utils; - /** * This class opens GUI that shows generator view for user. */ -public class DetailsPanel -{ - // --------------------------------------------------------------------- - // Section: Internal Constructor - // --------------------------------------------------------------------- - - - /** - * This is internal constructor. It is used internally in current class to avoid creating objects everywhere. - * - * @param addon Level object - * @param world World where user is operating - * @param user User who opens panel - */ - private DetailsPanel(Level addon, - World world, - User user) - { - this.addon = addon; - this.world = world; - this.user = user; - - this.island = this.addon.getIslands().getIsland(world, user); - - if (this.island != null) - { - this.levelsData = this.addon.getManager().getLevelsData(this.island); - } - else - { - this.levelsData = null; - } - - // By default no-filters are active. - this.activeTab = Tab.ALL_BLOCKS; - this.activeFilter = Filter.NAME; - this.materialCountList = new ArrayList<>(Material.values().length); - - this.updateFilters(); - } - - - /** - * This method builds this GUI. - */ - private void build() - { - if (this.island == null || this.levelsData == null) - { - // Nothing to see. - Utils.sendMessage(this.user, this.user.getTranslation("general.errors.no-island")); - return; - } - - if (this.levelsData.getMdCount().isEmpty() && this.levelsData.getUwCount().isEmpty()) - { - // Nothing to see. - Utils.sendMessage(this.user, this.user.getTranslation("level.conversations.no-data")); - return; - } - - // Start building panel. - TemplatedPanelBuilder panelBuilder = new TemplatedPanelBuilder(); - panelBuilder.user(this.user); - panelBuilder.world(this.user.getWorld()); - - panelBuilder.template("detail_panel", new File(this.addon.getDataFolder(), "panels")); - - panelBuilder.parameters("[name]", this.user.getName()); - - panelBuilder.registerTypeBuilder("NEXT", this::createNextButton); - panelBuilder.registerTypeBuilder("PREVIOUS", this::createPreviousButton); - panelBuilder.registerTypeBuilder("BLOCK", this::createMaterialButton); - - panelBuilder.registerTypeBuilder("FILTER", this::createFilterButton); - - // Register tabs - panelBuilder.registerTypeBuilder("TAB", this::createTabButton); - - // Register unknown type builder. - panelBuilder.build(); - } - - - /** - * This method updates filter of elements based on tabs. - */ - private void updateFilters() - { - this.materialCountList.clear(); - - switch (this.activeTab) - { - case ALL_BLOCKS -> { - Map materialCountMap = new EnumMap<>(Material.class); - - materialCountMap.putAll(this.levelsData.getMdCount()); - - // Add underwater blocks. - this.levelsData.getUwCount().forEach((material, count) -> materialCountMap.put(material, - materialCountMap.computeIfAbsent(material, key -> 0) + count)); - - materialCountMap.entrySet().stream().sorted((Map.Entry.comparingByKey())). - forEachOrdered(entry -> - this.materialCountList.add(new Pair<>(entry.getKey(), entry.getValue()))); - } - case ABOVE_SEA_LEVEL -> this.levelsData.getMdCount().entrySet().stream().sorted((Map.Entry.comparingByKey())) - .forEachOrdered(entry -> this.materialCountList.add(new Pair<>(entry.getKey(), entry.getValue()))); - - case UNDERWATER -> this.levelsData.getUwCount().entrySet().stream().sorted((Map.Entry.comparingByKey())) - .forEachOrdered(entry -> this.materialCountList.add(new Pair<>(entry.getKey(), entry.getValue()))); - - case SPAWNER -> { - int aboveWater = this.levelsData.getMdCount().getOrDefault(Material.SPAWNER, 0); - int underWater = this.levelsData.getUwCount().getOrDefault(Material.SPAWNER, 0); - - // TODO: spawners need some touch... - this.materialCountList.add(new Pair<>(Material.SPAWNER, underWater + aboveWater)); - } - } - - Comparator> sorter; - - switch (this.activeFilter) - { - case COUNT -> - { - sorter = (o1, o2) -> - { - if (o1.getValue().equals(o2.getValue())) - { - String o1Name = Utils.prettifyObject(o1.getKey(), this.user); - String o2Name = Utils.prettifyObject(o2.getKey(), this.user); - - return String.CASE_INSENSITIVE_ORDER.compare(o1Name, o2Name); - } - else - { - return Integer.compare(o2.getValue(), o1.getValue()); - } - }; - } - case VALUE -> - { - sorter = (o1, o2) -> - { - int blockLimit = this.addon.getBlockConfig().getBlockLimits().getOrDefault(o1.getKey(), 0); - int o1Count = blockLimit > 0 ? Math.min(o1.getValue(), blockLimit) : o1.getValue(); - - blockLimit = this.addon.getBlockConfig().getBlockLimits().getOrDefault(o2.getKey(), 0); - int o2Count = blockLimit > 0 ? Math.min(o2.getValue(), blockLimit) : o2.getValue(); - - long o1Value = (long) o1Count * - this.addon.getBlockConfig().getBlockValues().getOrDefault(o1.getKey(), 0); - long o2Value = (long) o2Count * - this.addon.getBlockConfig().getBlockValues().getOrDefault(o2.getKey(), 0); - - if (o1Value == o2Value) - { - String o1Name = Utils.prettifyObject(o1.getKey(), this.user); - String o2Name = Utils.prettifyObject(o2.getKey(), this.user); - - return String.CASE_INSENSITIVE_ORDER.compare(o1Name, o2Name); - } - else - { - return Long.compare(o2Value, o1Value); - } - }; - } - default -> - { - sorter = (o1, o2) -> - { - String o1Name = Utils.prettifyObject(o1.getKey(), this.user); - String o2Name = Utils.prettifyObject(o2.getKey(), this.user); - - return String.CASE_INSENSITIVE_ORDER.compare(o1Name, o2Name); - }; - } - } - - this.materialCountList.sort(sorter); - - this.pageIndex = 0; - } - - - // --------------------------------------------------------------------- - // Section: Tab Button Type - // --------------------------------------------------------------------- - - - /** - * Create tab button panel item. - * - * @param template the template - * @param slot the slot - * @return the panel item - */ - private PanelItem createTabButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) - { - PanelItemBuilder builder = new PanelItemBuilder(); - - if (template.icon() != null) - { - // Set icon - builder.icon(template.icon().clone()); - } - - if (template.title() != null) - { - // Set title - builder.name(this.user.getTranslation(this.world, template.title())); - } - - if (template.description() != null) - { - // Set description - builder.description(this.user.getTranslation(this.world, template.description())); - } - - Tab tab = Enums.getIfPresent(Tab.class, String.valueOf(template.dataMap().get("tab"))).or(Tab.ALL_BLOCKS); - - // Get only possible actions, by removing all inactive ones. - List activeActions = new ArrayList<>(template.actions()); - - activeActions.removeIf(action -> - "VIEW".equalsIgnoreCase(action.actionType()) && this.activeTab == tab); - - // Add Click handler - builder.clickHandler((panel, user, clickType, i) -> - { - for (ItemTemplateRecord.ActionRecords action : activeActions) - { - if ((clickType == action.clickType() || ClickType.UNKNOWN.equals(action.clickType())) - && "VIEW".equalsIgnoreCase(action.actionType())) - { - this.activeTab = tab; - - // Update filters. - this.updateFilters(); - this.build(); - } - } - - return true; - }); - - // Collect tooltips. - List tooltips = activeActions.stream(). - filter(action -> action.tooltip() != null). - map(action -> this.user.getTranslation(this.world, action.tooltip())). - filter(text -> !text.isBlank()). - collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); - - // Add tooltips. - if (!tooltips.isEmpty()) - { - // Empty line and tooltips. - builder.description(""); - builder.description(tooltips); - } - - builder.glow(this.activeTab == tab); - - return builder.build(); - } - - - /** - * Create next button panel item. - * - * @param template the template - * @param slot the slot - * @return the panel item - */ - private PanelItem createFilterButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) - { - PanelItemBuilder builder = new PanelItemBuilder(); - - if (template.icon() != null) - { - // Set icon - builder.icon(template.icon().clone()); - } - - Filter filter; - - if (slot.amountMap().getOrDefault("FILTER", 0) > 1) - { - filter = Enums.getIfPresent(Filter.class, String.valueOf(template.dataMap().get("filter"))).or(Filter.NAME); - } - else - { - filter = this.activeFilter; - } - - final String reference = "level.gui.buttons.filters."; - - if (template.title() != null) - { - // Set title - builder.name(this.user.getTranslation(this.world, template.title().replace("[filter]", filter.name().toLowerCase()))); - } - else - { - builder.name(this.user.getTranslation(this.world, reference + filter.name().toLowerCase() + ".name")); - } - - if (template.description() != null) - { - // Set description - builder.description(this.user.getTranslation(this.world, template.description().replace("[filter]", filter.name().toLowerCase()))); - } - else - { - builder.name(this.user.getTranslation(this.world, reference + filter.name().toLowerCase() + ".description")); - } - - // Get only possible actions, by removing all inactive ones. - List activeActions = new ArrayList<>(template.actions()); - - // Add Click handler - builder.clickHandler((panel, user, clickType, i) -> - { - for (ItemTemplateRecord.ActionRecords action : activeActions) - { - if (clickType == action.clickType() || ClickType.UNKNOWN.equals(action.clickType())) - { - if ("UP".equalsIgnoreCase(action.actionType())) - { - this.activeFilter = Utils.getNextValue(Filter.values(), filter); - - // Update filters. - this.updateFilters(); - this.build(); - } - else if ("DOWN".equalsIgnoreCase(action.actionType())) - { - this.activeFilter = Utils.getPreviousValue(Filter.values(), filter); - - // Update filters. - this.updateFilters(); - this.build(); - } - else if ("SELECT".equalsIgnoreCase(action.actionType())) - { - this.activeFilter = filter; - - // Update filters. - this.updateFilters(); - this.build(); - } - } - } - - return true; - }); - - // Collect tooltips. - List tooltips = activeActions.stream(). - filter(action -> action.tooltip() != null). - map(action -> this.user.getTranslation(this.world, action.tooltip())). - filter(text -> !text.isBlank()). - collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); - - // Add tooltips. - if (!tooltips.isEmpty()) - { - // Empty line and tooltips. - builder.description(""); - builder.description(tooltips); - } - - builder.glow(this.activeFilter == filter); - - return builder.build(); - } - - - // --------------------------------------------------------------------- - // Section: Create common buttons - // --------------------------------------------------------------------- - - - /** - * Create next button panel item. - * - * @param template the template - * @param slot the slot - * @return the panel item - */ - private PanelItem createNextButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) - { - long size = this.materialCountList.size(); - - if (size <= slot.amountMap().getOrDefault("BLOCK", 1) || - 1.0 * size / slot.amountMap().getOrDefault("BLOCK", 1) <= this.pageIndex + 1) - { - // There are no next elements - return null; - } - - int nextPageIndex = this.pageIndex + 2; - - PanelItemBuilder builder = new PanelItemBuilder(); - - if (template.icon() != null) - { - ItemStack clone = template.icon().clone(); - - if (Boolean.TRUE.equals(template.dataMap().getOrDefault("indexing", false))) - { - clone.setAmount(nextPageIndex); - } - - builder.icon(clone); - } - - if (template.title() != null) - { - builder.name(this.user.getTranslation(this.world, template.title())); - } - - if (template.description() != null) - { - builder.description(this.user.getTranslation(this.world, template.description(), - TextVariables.NUMBER, String.valueOf(nextPageIndex))); - } - - // Add ClickHandler - builder.clickHandler((panel, user, clickType, i) -> - { - for (ItemTemplateRecord.ActionRecords action : template.actions()) - { - if ((clickType == action.clickType() || ClickType.UNKNOWN.equals(action.clickType())) && - "NEXT".equalsIgnoreCase(action.actionType())) - { - this.pageIndex++; - this.build(); - } - } - - // Always return true. - return true; - }); - - // Collect tooltips. - List tooltips = template.actions().stream(). - filter(action -> action.tooltip() != null). - map(action -> this.user.getTranslation(this.world, action.tooltip())). - filter(text -> !text.isBlank()). - collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); - - // Add tooltips. - if (!tooltips.isEmpty()) - { - // Empty line and tooltips. - builder.description(""); - builder.description(tooltips); - } - - return builder.build(); - } - - - /** - * Create previous button panel item. - * - * @param template the template - * @param slot the slot - * @return the panel item - */ - private PanelItem createPreviousButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) - { - if (this.pageIndex == 0) - { - // There are no next elements - return null; - } - - int previousPageIndex = this.pageIndex; - - PanelItemBuilder builder = new PanelItemBuilder(); - - if (template.icon() != null) - { - ItemStack clone = template.icon().clone(); - - if (Boolean.TRUE.equals(template.dataMap().getOrDefault("indexing", false))) - { - clone.setAmount(previousPageIndex); - } - - builder.icon(clone); - } - - if (template.title() != null) - { - builder.name(this.user.getTranslation(this.world, template.title())); - } - - if (template.description() != null) - { - builder.description(this.user.getTranslation(this.world, template.description(), - TextVariables.NUMBER, String.valueOf(previousPageIndex))); - } - - // Add ClickHandler - builder.clickHandler((panel, user, clickType, i) -> - { - for (ItemTemplateRecord.ActionRecords action : template.actions()) - { - if ((clickType == action.clickType() || ClickType.UNKNOWN.equals(action.clickType())) - && "PREVIOUS".equalsIgnoreCase(action.actionType())) - { - this.pageIndex--; - this.build(); - } - } - - // Always return true. - return true; - }); - - // Collect tooltips. - List tooltips = template.actions().stream(). - filter(action -> action.tooltip() != null). - map(action -> this.user.getTranslation(this.world, action.tooltip())). - filter(text -> !text.isBlank()). - collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); - - // Add tooltips. - if (!tooltips.isEmpty()) - { - // Empty line and tooltips. - builder.description(""); - builder.description(tooltips); - } - - return builder.build(); - } - - - // --------------------------------------------------------------------- - // Section: Create Material Button - // --------------------------------------------------------------------- - - - /** - * Create material button panel item. - * - * @param template the template - * @param slot the slot - * @return the panel item - */ - private PanelItem createMaterialButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) - { - if (this.materialCountList.isEmpty()) - { - // Does not contain any generators. - return null; - } - - int index = this.pageIndex * slot.amountMap().getOrDefault("BLOCK", 1) + slot.slot(); - - if (index >= this.materialCountList.size()) - { - // Out of index. - return null; - } - - return this.createMaterialButton(template, this.materialCountList.get(index)); - } - - - /** - * This method creates button for material. - * - * @param template the template of the button - * @param materialCount materialCount which button must be created. - * @return PanelItem for generator tier. - */ - private PanelItem createMaterialButton(ItemTemplateRecord template, - Pair materialCount) - { - PanelItemBuilder builder = new PanelItemBuilder(); - - if (template.icon() != null) - { - builder.icon(template.icon().clone()); - } - else - { - builder.icon(PanelUtils.getMaterialItem(materialCount.getKey())); - } - - if (materialCount.getValue() < 64) - { - builder.amount(materialCount.getValue()); - } - - if (template.title() != null) - { - builder.name(this.user.getTranslation(this.world, template.title(), - TextVariables.NUMBER, String.valueOf(materialCount.getValue()), - "[material]", Utils.prettifyObject(materialCount.getKey(), this.user))); - } - - String description = Utils.prettifyDescription(materialCount.getKey(), this.user); - - final String reference = "level.gui.buttons.material."; - String blockId = this.user.getTranslationOrNothing(reference + "id", - "[id]", materialCount.getKey().name()); - - int blockValue = this.addon.getBlockConfig().getBlockValues().getOrDefault(materialCount.getKey(), 0); - String value = blockValue > 0 ? this.user.getTranslationOrNothing(reference + "value", - TextVariables.NUMBER, String.valueOf(blockValue)) : ""; - - int blockLimit = this.addon.getBlockConfig().getBlockLimits().getOrDefault(materialCount.getKey(), 0); - String limit = blockLimit > 0 ? this.user.getTranslationOrNothing(reference + "limit", - TextVariables.NUMBER, String.valueOf(blockLimit)) : ""; - - String count = this.user.getTranslationOrNothing(reference + "count", - TextVariables.NUMBER, String.valueOf(materialCount.getValue())); - - long calculatedValue = (long) Math.min(blockLimit > 0 ? blockLimit : Integer.MAX_VALUE, materialCount.getValue()) * blockValue; - String valueText = calculatedValue > 0 ? this.user.getTranslationOrNothing(reference + "calculated", - TextVariables.NUMBER, String.valueOf(calculatedValue)) : ""; - - if (template.description() != null) - { - builder.description(this.user.getTranslation(this.world, template.description(), - "[description]", description, - "[id]", blockId, - "[value]", value, - "[calculated]", valueText, - "[limit]", limit, - "[count]", count). - replaceAll("(?m)^[ \\t]*\\r?\\n", ""). - replaceAll("(?> materialCountList; - - /** - * This variable holds current pageIndex for multi-page generator choosing. - */ - private int pageIndex; - - /** - * This variable stores which tab currently is active. - */ - private Tab activeTab; - - /** - * This variable stores active filter for items. - */ - private Filter activeFilter; +public class DetailsPanel { + // --------------------------------------------------------------------- + // Section: Internal Constructor + // --------------------------------------------------------------------- + + /** + * This is internal constructor. It is used internally in current class to avoid + * creating objects everywhere. + * + * @param addon Level object + * @param world World where user is operating + * @param user User who opens panel + */ + private DetailsPanel(Level addon, World world, User user) { + this.addon = addon; + this.world = world; + this.user = user; + + this.island = this.addon.getIslands().getIsland(world, user); + + if (this.island != null) { + this.levelsData = this.addon.getManager().getLevelsData(this.island); + } else { + this.levelsData = null; + } + + // By default no-filters are active. + this.activeTab = Tab.ALL_BLOCKS; + this.activeFilter = Filter.NAME; + this.materialCountList = new ArrayList<>(Material.values().length); + + this.updateFilters(); + } + + /** + * This method builds this GUI. + */ + private void build() { + if (this.island == null || this.levelsData == null) { + // Nothing to see. + Utils.sendMessage(this.user, this.user.getTranslation("general.errors.no-island")); + return; + } + + if (this.levelsData.getMdCount().isEmpty() && this.levelsData.getUwCount().isEmpty()) { + // Nothing to see. + Utils.sendMessage(this.user, this.user.getTranslation("level.conversations.no-data")); + return; + } + + // Start building panel. + TemplatedPanelBuilder panelBuilder = new TemplatedPanelBuilder(); + panelBuilder.user(this.user); + panelBuilder.world(this.user.getWorld()); + + panelBuilder.template("detail_panel", new File(this.addon.getDataFolder(), "panels")); + + panelBuilder.parameters("[name]", this.user.getName()); + + panelBuilder.registerTypeBuilder("NEXT", this::createNextButton); + panelBuilder.registerTypeBuilder("PREVIOUS", this::createPreviousButton); + panelBuilder.registerTypeBuilder("BLOCK", this::createMaterialButton); + + panelBuilder.registerTypeBuilder("FILTER", this::createFilterButton); + + // Register tabs + panelBuilder.registerTypeBuilder("TAB", this::createTabButton); + + // Register unknown type builder. + panelBuilder.build(); + } + + /** + * This method updates filter of elements based on tabs. + */ + private void updateFilters() { + this.materialCountList.clear(); + + switch (this.activeTab) { + case ALL_BLOCKS -> { + Map materialCountMap = new EnumMap<>(Material.class); + + materialCountMap.putAll(this.levelsData.getMdCount()); + + // Add underwater blocks. + this.levelsData.getUwCount().forEach((material, count) -> materialCountMap.put(material, + materialCountMap.computeIfAbsent(material, key -> 0) + count)); + + materialCountMap.entrySet().stream().sorted((Map.Entry.comparingByKey())) + .forEachOrdered(entry -> this.materialCountList.add(new Pair<>(entry.getKey(), entry.getValue()))); + } + case ABOVE_SEA_LEVEL -> this.levelsData.getMdCount().entrySet().stream().sorted((Map.Entry.comparingByKey())) + .forEachOrdered(entry -> this.materialCountList.add(new Pair<>(entry.getKey(), entry.getValue()))); + + case UNDERWATER -> this.levelsData.getUwCount().entrySet().stream().sorted((Map.Entry.comparingByKey())) + .forEachOrdered(entry -> this.materialCountList.add(new Pair<>(entry.getKey(), entry.getValue()))); + + case SPAWNER -> { + int aboveWater = this.levelsData.getMdCount().getOrDefault(Material.SPAWNER, 0); + int underWater = this.levelsData.getUwCount().getOrDefault(Material.SPAWNER, 0); + + // TODO: spawners need some touch... + this.materialCountList.add(new Pair<>(Material.SPAWNER, underWater + aboveWater)); + } + } + + Comparator> sorter; + + switch (this.activeFilter) { + case COUNT -> { + sorter = (o1, o2) -> { + if (o1.getValue().equals(o2.getValue())) { + String o1Name = Utils.prettifyObject(o1.getKey(), this.user); + String o2Name = Utils.prettifyObject(o2.getKey(), this.user); + + return String.CASE_INSENSITIVE_ORDER.compare(o1Name, o2Name); + } else { + return Integer.compare(o2.getValue(), o1.getValue()); + } + }; + } + case VALUE -> { + sorter = (o1, o2) -> { + int blockLimit = this.addon.getBlockConfig().getBlockLimits().getOrDefault(o1.getKey(), 0); + int o1Count = blockLimit > 0 ? Math.min(o1.getValue(), blockLimit) : o1.getValue(); + + blockLimit = this.addon.getBlockConfig().getBlockLimits().getOrDefault(o2.getKey(), 0); + int o2Count = blockLimit > 0 ? Math.min(o2.getValue(), blockLimit) : o2.getValue(); + + long o1Value = (long) o1Count + * this.addon.getBlockConfig().getBlockValues().getOrDefault(o1.getKey(), 0); + long o2Value = (long) o2Count + * this.addon.getBlockConfig().getBlockValues().getOrDefault(o2.getKey(), 0); + + if (o1Value == o2Value) { + String o1Name = Utils.prettifyObject(o1.getKey(), this.user); + String o2Name = Utils.prettifyObject(o2.getKey(), this.user); + + return String.CASE_INSENSITIVE_ORDER.compare(o1Name, o2Name); + } else { + return Long.compare(o2Value, o1Value); + } + }; + } + default -> { + sorter = (o1, o2) -> { + String o1Name = Utils.prettifyObject(o1.getKey(), this.user); + String o2Name = Utils.prettifyObject(o2.getKey(), this.user); + + return String.CASE_INSENSITIVE_ORDER.compare(o1Name, o2Name); + }; + } + } + + this.materialCountList.sort(sorter); + + this.pageIndex = 0; + } + + // --------------------------------------------------------------------- + // Section: Tab Button Type + // --------------------------------------------------------------------- + + /** + * Create tab button panel item. + * + * @param template the template + * @param slot the slot + * @return the panel item + */ + private PanelItem createTabButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { + PanelItemBuilder builder = new PanelItemBuilder(); + + if (template.icon() != null) { + // Set icon + builder.icon(template.icon().clone()); + } + + if (template.title() != null) { + // Set title + builder.name(this.user.getTranslation(this.world, template.title())); + } + + if (template.description() != null) { + // Set description + builder.description(this.user.getTranslation(this.world, template.description())); + } + + Tab tab = Enums.getIfPresent(Tab.class, String.valueOf(template.dataMap().get("tab"))).or(Tab.ALL_BLOCKS); + + // Get only possible actions, by removing all inactive ones. + List activeActions = new ArrayList<>(template.actions()); + + activeActions.removeIf(action -> "VIEW".equalsIgnoreCase(action.actionType()) && this.activeTab == tab); + + // Add Click handler + builder.clickHandler((panel, user, clickType, i) -> { + for (ItemTemplateRecord.ActionRecords action : activeActions) { + if ((clickType == action.clickType() || ClickType.UNKNOWN.equals(action.clickType())) + && "VIEW".equalsIgnoreCase(action.actionType())) { + this.activeTab = tab; + + // Update filters. + this.updateFilters(); + this.build(); + } + } + + return true; + }); + + // Collect tooltips. + List tooltips = activeActions.stream().filter(action -> action.tooltip() != null) + .map(action -> this.user.getTranslation(this.world, action.tooltip())).filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); + + // Add tooltips. + if (!tooltips.isEmpty()) { + // Empty line and tooltips. + builder.description(""); + builder.description(tooltips); + } + + builder.glow(this.activeTab == tab); + + return builder.build(); + } + + /** + * Create next button panel item. + * + * @param template the template + * @param slot the slot + * @return the panel item + */ + private PanelItem createFilterButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { + PanelItemBuilder builder = new PanelItemBuilder(); + + if (template.icon() != null) { + // Set icon + builder.icon(template.icon().clone()); + } + + Filter filter; + + if (slot.amountMap().getOrDefault("FILTER", 0) > 1) { + filter = Enums.getIfPresent(Filter.class, String.valueOf(template.dataMap().get("filter"))).or(Filter.NAME); + } else { + filter = this.activeFilter; + } + + final String reference = "level.gui.buttons.filters."; + + if (template.title() != null) { + // Set title + builder.name(this.user.getTranslation(this.world, + template.title().replace("[filter]", filter.name().toLowerCase()))); + } else { + builder.name(this.user.getTranslation(this.world, reference + filter.name().toLowerCase() + ".name")); + } + + if (template.description() != null) { + // Set description + builder.description(this.user.getTranslation(this.world, + template.description().replace("[filter]", filter.name().toLowerCase()))); + } else { + builder.name( + this.user.getTranslation(this.world, reference + filter.name().toLowerCase() + ".description")); + } + + // Get only possible actions, by removing all inactive ones. + List activeActions = new ArrayList<>(template.actions()); + + // Add Click handler + builder.clickHandler((panel, user, clickType, i) -> { + for (ItemTemplateRecord.ActionRecords action : activeActions) { + if (clickType == action.clickType() || ClickType.UNKNOWN.equals(action.clickType())) { + if ("UP".equalsIgnoreCase(action.actionType())) { + this.activeFilter = Utils.getNextValue(Filter.values(), filter); + + // Update filters. + this.updateFilters(); + this.build(); + } else if ("DOWN".equalsIgnoreCase(action.actionType())) { + this.activeFilter = Utils.getPreviousValue(Filter.values(), filter); + + // Update filters. + this.updateFilters(); + this.build(); + } else if ("SELECT".equalsIgnoreCase(action.actionType())) { + this.activeFilter = filter; + + // Update filters. + this.updateFilters(); + this.build(); + } + } + } + + return true; + }); + + // Collect tooltips. + List tooltips = activeActions.stream().filter(action -> action.tooltip() != null) + .map(action -> this.user.getTranslation(this.world, action.tooltip())).filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); + + // Add tooltips. + if (!tooltips.isEmpty()) { + // Empty line and tooltips. + builder.description(""); + builder.description(tooltips); + } + + builder.glow(this.activeFilter == filter); + + return builder.build(); + } + + // --------------------------------------------------------------------- + // Section: Create common buttons + // --------------------------------------------------------------------- + + /** + * Create next button panel item. + * + * @param template the template + * @param slot the slot + * @return the panel item + */ + private PanelItem createNextButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { + long size = this.materialCountList.size(); + + if (size <= slot.amountMap().getOrDefault("BLOCK", 1) + || 1.0 * size / slot.amountMap().getOrDefault("BLOCK", 1) <= this.pageIndex + 1) { + // There are no next elements + return null; + } + + int nextPageIndex = this.pageIndex + 2; + + PanelItemBuilder builder = new PanelItemBuilder(); + + if (template.icon() != null) { + ItemStack clone = template.icon().clone(); + + if (Boolean.TRUE.equals(template.dataMap().getOrDefault("indexing", false))) { + clone.setAmount(nextPageIndex); + } + + builder.icon(clone); + } + + if (template.title() != null) { + builder.name(this.user.getTranslation(this.world, template.title())); + } + + if (template.description() != null) { + builder.description(this.user.getTranslation(this.world, template.description(), TextVariables.NUMBER, + String.valueOf(nextPageIndex))); + } + + // Add ClickHandler + builder.clickHandler((panel, user, clickType, i) -> { + for (ItemTemplateRecord.ActionRecords action : template.actions()) { + if ((clickType == action.clickType() || ClickType.UNKNOWN.equals(action.clickType())) + && "NEXT".equalsIgnoreCase(action.actionType())) { + this.pageIndex++; + this.build(); + } + } + + // Always return true. + return true; + }); + + // Collect tooltips. + List tooltips = template.actions().stream().filter(action -> action.tooltip() != null) + .map(action -> this.user.getTranslation(this.world, action.tooltip())).filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); + + // Add tooltips. + if (!tooltips.isEmpty()) { + // Empty line and tooltips. + builder.description(""); + builder.description(tooltips); + } + + return builder.build(); + } + + /** + * Create previous button panel item. + * + * @param template the template + * @param slot the slot + * @return the panel item + */ + private PanelItem createPreviousButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { + if (this.pageIndex == 0) { + // There are no next elements + return null; + } + + int previousPageIndex = this.pageIndex; + + PanelItemBuilder builder = new PanelItemBuilder(); + + if (template.icon() != null) { + ItemStack clone = template.icon().clone(); + + if (Boolean.TRUE.equals(template.dataMap().getOrDefault("indexing", false))) { + clone.setAmount(previousPageIndex); + } + + builder.icon(clone); + } + + if (template.title() != null) { + builder.name(this.user.getTranslation(this.world, template.title())); + } + + if (template.description() != null) { + builder.description(this.user.getTranslation(this.world, template.description(), TextVariables.NUMBER, + String.valueOf(previousPageIndex))); + } + + // Add ClickHandler + builder.clickHandler((panel, user, clickType, i) -> { + for (ItemTemplateRecord.ActionRecords action : template.actions()) { + if ((clickType == action.clickType() || ClickType.UNKNOWN.equals(action.clickType())) + && "PREVIOUS".equalsIgnoreCase(action.actionType())) { + this.pageIndex--; + this.build(); + } + } + + // Always return true. + return true; + }); + + // Collect tooltips. + List tooltips = template.actions().stream().filter(action -> action.tooltip() != null) + .map(action -> this.user.getTranslation(this.world, action.tooltip())).filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); + + // Add tooltips. + if (!tooltips.isEmpty()) { + // Empty line and tooltips. + builder.description(""); + builder.description(tooltips); + } + + return builder.build(); + } + + // --------------------------------------------------------------------- + // Section: Create Material Button + // --------------------------------------------------------------------- + + /** + * Create material button panel item. + * + * @param template the template + * @param slot the slot + * @return the panel item + */ + private PanelItem createMaterialButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { + if (this.materialCountList.isEmpty()) { + // Does not contain any generators. + return null; + } + + int index = this.pageIndex * slot.amountMap().getOrDefault("BLOCK", 1) + slot.slot(); + + if (index >= this.materialCountList.size()) { + // Out of index. + return null; + } + + return this.createMaterialButton(template, this.materialCountList.get(index)); + } + + /** + * This method creates button for material. + * + * @param template the template of the button + * @param materialCount materialCount which button must be created. + * @return PanelItem for generator tier. + */ + private PanelItem createMaterialButton(ItemTemplateRecord template, Pair materialCount) { + PanelItemBuilder builder = new PanelItemBuilder(); + + if (template.icon() != null) { + builder.icon(template.icon().clone()); + } else { + builder.icon(PanelUtils.getMaterialItem(materialCount.getKey())); + } + + if (materialCount.getValue() < 64) { + builder.amount(materialCount.getValue()); + } + + if (template.title() != null) { + builder.name(this.user.getTranslation(this.world, template.title(), TextVariables.NUMBER, + String.valueOf(materialCount.getValue()), "[material]", + Utils.prettifyObject(materialCount.getKey(), this.user))); + } + + String description = Utils.prettifyDescription(materialCount.getKey(), this.user); + + final String reference = "level.gui.buttons.material."; + String blockId = this.user.getTranslationOrNothing(reference + "id", "[id]", materialCount.getKey().name()); + + int blockValue = this.addon.getBlockConfig().getBlockValues().getOrDefault(materialCount.getKey(), 0); + String value = blockValue > 0 + ? this.user.getTranslationOrNothing(reference + "value", TextVariables.NUMBER, + String.valueOf(blockValue)) + : ""; + + int blockLimit = this.addon.getBlockConfig().getBlockLimits().getOrDefault(materialCount.getKey(), 0); + String limit = blockLimit > 0 + ? this.user.getTranslationOrNothing(reference + "limit", TextVariables.NUMBER, + String.valueOf(blockLimit)) + : ""; + + String count = this.user.getTranslationOrNothing(reference + "count", TextVariables.NUMBER, + String.valueOf(materialCount.getValue())); + + long calculatedValue = (long) Math.min(blockLimit > 0 ? blockLimit : Integer.MAX_VALUE, + materialCount.getValue()) * blockValue; + String valueText = calculatedValue > 0 ? this.user.getTranslationOrNothing(reference + "calculated", + TextVariables.NUMBER, String.valueOf(calculatedValue)) : ""; + + if (template.description() != null) { + builder.description(this.user + .getTranslation(this.world, template.description(), "[description]", description, "[id]", blockId, + "[value]", value, "[calculated]", valueText, "[limit]", limit, "[count]", count) + .replaceAll("(?m)^[ \\t]*\\r?\\n", "").replaceAll("(?> materialCountList; + + /** + * This variable holds current pageIndex for multi-page generator choosing. + */ + private int pageIndex; + + /** + * This variable stores which tab currently is active. + */ + private Tab activeTab; + + /** + * This variable stores active filter for items. + */ + private Filter activeFilter; } diff --git a/src/test/java/world/bentobox/level/LevelsManagerTest.java b/src/test/java/world/bentobox/level/LevelsManagerTest.java index 5b18aa5..e077de0 100644 --- a/src/test/java/world/bentobox/level/LevelsManagerTest.java +++ b/src/test/java/world/bentobox/level/LevelsManagerTest.java @@ -70,65 +70,63 @@ * */ @RunWith(PowerMockRunner.class) -@PrepareForTest({Bukkit.class, BentoBox.class, DatabaseSetup.class, PanelBuilder.class}) +@PrepareForTest({ Bukkit.class, BentoBox.class, DatabaseSetup.class, PanelBuilder.class }) public class LevelsManagerTest { - @Mock - private static AbstractDatabaseHandler handler; - @Mock - Level addon; - @Mock - private BentoBox plugin; - @Mock - private Settings pluginSettings; - - - // Class under test - private LevelsManager lm; - @Mock - private Island island; - @Mock - private Pipeliner pipeliner; - private CompletableFuture cf; - private UUID uuid; - @Mock - private World world; - @Mock - private Player player; - @Mock - private ConfigSettings settings; - @Mock - private User user; - @Mock - private PlayersManager pm; - @Mock - private Inventory inv; - @Mock - private IslandWorldManager iwm; - @Mock - private PluginManager pim; - @Mock - private IslandLevels levelsData; - @Mock - private IslandsManager im; - @Mock - private BukkitScheduler scheduler; - - - - @SuppressWarnings("unchecked") - @BeforeClass - public static void beforeClass() { - // This has to be done beforeClass otherwise the tests will interfere with each other - handler = mock(AbstractDatabaseHandler.class); - // Database - PowerMockito.mockStatic(DatabaseSetup.class); - DatabaseSetup dbSetup = mock(DatabaseSetup.class); - when(DatabaseSetup.getDatabase()).thenReturn(dbSetup); - when(dbSetup.getHandler(any())).thenReturn(handler); - } - - /** + @Mock + private static AbstractDatabaseHandler handler; + @Mock + Level addon; + @Mock + private BentoBox plugin; + @Mock + private Settings pluginSettings; + + // Class under test + private LevelsManager lm; + @Mock + private Island island; + @Mock + private Pipeliner pipeliner; + private CompletableFuture cf; + private UUID uuid; + @Mock + private World world; + @Mock + private Player player; + @Mock + private ConfigSettings settings; + @Mock + private User user; + @Mock + private PlayersManager pm; + @Mock + private Inventory inv; + @Mock + private IslandWorldManager iwm; + @Mock + private PluginManager pim; + @Mock + private IslandLevels levelsData; + @Mock + private IslandsManager im; + @Mock + private BukkitScheduler scheduler; + + @SuppressWarnings("unchecked") + @BeforeClass + public static void beforeClass() { + // This has to be done beforeClass otherwise the tests will interfere with each + // other + handler = mock(AbstractDatabaseHandler.class); + // Database + PowerMockito.mockStatic(DatabaseSetup.class); + DatabaseSetup dbSetup = mock(DatabaseSetup.class); + when(DatabaseSetup.getDatabase()).thenReturn(dbSetup); + when(dbSetup.getHandler(any())).thenReturn(handler); + } + + /** * @throws java.lang.Exception */ @SuppressWarnings("unchecked") @@ -164,8 +162,7 @@ public void setUp() throws Exception { when(island.getWorld()).thenReturn(world); when(island.getUniqueId()).thenReturn(UUID.randomUUID().toString()); // Default to uuid's being island owners - when(im.isOwner(eq(world), any())).thenReturn(true); - when(im.getOwner(any(), any(UUID.class))).thenAnswer(in -> in.getArgument(1, UUID.class)); + when(im.hasIsland(eq(world), any(UUID.class))).thenReturn(true); when(im.getIsland(world, uuid)).thenReturn(island); when(im.getIslandById(anyString())).thenReturn(Optional.of(island)); @@ -235,220 +232,229 @@ public void setUp() throws Exception { lm.migrate(); } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - deleteAll(new File("database")); - User.clearUsers(); - Mockito.framework().clearInlineMocks(); - } - - private static void deleteAll(File file) throws IOException { - if (file.exists()) { - Files.walk(file.toPath()) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#calculateLevel(UUID, world.bentobox.bentobox.database.objects.Island)}. - */ - @Test - public void testCalculateLevel() { - Results results = new Results(); - results.setLevel(10000); - results.setInitialLevel(3); - lm.calculateLevel(uuid, island); - // Complete the pipelined completable future - cf.complete(results); - - assertEquals(10000L, lm.getLevelsData(island).getLevel()); - //Map tt = lm.getTopTen(world, 10); - //assertEquals(1, tt.size()); - //assertTrue(tt.get(uuid) == 10000); - assertEquals(10000L, lm.getIslandMaxLevel(world, uuid)); - - results.setLevel(5000); - lm.calculateLevel(uuid, island); - // Complete the pipelined completable future - cf.complete(results); - assertEquals(5000L, lm.getLevelsData(island).getLevel()); - // Still should be 10000 - assertEquals(10000L, lm.getIslandMaxLevel(world, uuid)); - - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#getInitialLevel(world.bentobox.bentobox.database.objects.Island)}. - */ - @Test - public void testGetInitialLevel() { - assertEquals(0,lm.getInitialLevel(island)); - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#getIslandLevel(org.bukkit.World, java.util.UUID)}. - */ - @Test - public void testGetIslandLevel() { - assertEquals(-5, lm.getIslandLevel(world, uuid)); - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#getPointsToNextString(org.bukkit.World, java.util.UUID)}. - */ - @Test - public void testGetPointsToNextString() { - // No island player - assertEquals("", lm.getPointsToNextString(world, UUID.randomUUID())); - // Player has island - assertEquals("0", lm.getPointsToNextString(world, uuid)); - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#getIslandLevelString(org.bukkit.World, java.util.UUID)}. - */ - @Test - public void testGetIslandLevelString() { - assertEquals("-5", lm.getIslandLevelString(world, uuid)); - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#getLevelsData(java.util.UUID)}. - */ - @Test - public void testGetLevelsData() { - assertEquals(levelsData, lm.getLevelsData(island)); - - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#formatLevel(long)}. - */ - @Test - public void testFormatLevel() { - assertEquals("123456789", lm.formatLevel(123456789L)); - when(settings.isShorthand()).thenReturn(true); - assertEquals("123.5M", lm.formatLevel(123456789L)); - assertEquals("1.2k", lm.formatLevel(1234L)); - assertEquals("123.5G", lm.formatLevel(123456789352L)); - assertEquals("1.2T", lm.formatLevel(1234567893524L)); - assertEquals("12345.7T", lm.formatLevel(12345678345345349L)); - - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#getTopTen(org.bukkit.World, int)}. - */ - @Test - public void testGetTopTenEmpty() { - Map tt = lm.getTopTen(world, Level.TEN); - assertTrue(tt.isEmpty()); - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#getTopTen(org.bukkit.World, int)}. - */ - @Test - public void testGetTopTen() { - testLoadTopTens(); - Map tt = lm.getTopTen(world, Level.TEN); - assertFalse(tt.isEmpty()); - assertEquals(1, tt.size()); - assertEquals(1, lm.getTopTen(world, 1).size()); - } - - /** + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + deleteAll(new File("database")); + User.clearUsers(); + Mockito.framework().clearInlineMocks(); + } + + private static void deleteAll(File file) throws IOException { + if (file.exists()) { + Files.walk(file.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#calculateLevel(UUID, world.bentobox.bentobox.database.objects.Island)}. + */ + @Test + public void testCalculateLevel() { + Results results = new Results(); + results.setLevel(10000); + results.setInitialLevel(3); + lm.calculateLevel(uuid, island); + // Complete the pipelined completable future + cf.complete(results); + + assertEquals(10000L, lm.getLevelsData(island).getLevel()); + // Map tt = lm.getTopTen(world, 10); + // assertEquals(1, tt.size()); + // assertTrue(tt.get(uuid) == 10000); + assertEquals(10000L, lm.getIslandMaxLevel(world, uuid)); + + results.setLevel(5000); + lm.calculateLevel(uuid, island); + // Complete the pipelined completable future + cf.complete(results); + assertEquals(5000L, lm.getLevelsData(island).getLevel()); + // Still should be 10000 + assertEquals(10000L, lm.getIslandMaxLevel(world, uuid)); + + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#getInitialLevel(world.bentobox.bentobox.database.objects.Island)}. + */ + @Test + public void testGetInitialLevel() { + assertEquals(0, lm.getInitialLevel(island)); + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#getIslandLevel(org.bukkit.World, java.util.UUID)}. + */ + @Test + public void testGetIslandLevel() { + assertEquals(-5, lm.getIslandLevel(world, uuid)); + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#getPointsToNextString(org.bukkit.World, java.util.UUID)}. + */ + @Test + public void testGetPointsToNextString() { + // No island player + assertEquals("", lm.getPointsToNextString(world, UUID.randomUUID())); + // Player has island + assertEquals("0", lm.getPointsToNextString(world, uuid)); + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#getIslandLevelString(org.bukkit.World, java.util.UUID)}. + */ + @Test + public void testGetIslandLevelString() { + assertEquals("-5", lm.getIslandLevelString(world, uuid)); + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#getLevelsData(java.util.UUID)}. + */ + @Test + public void testGetLevelsData() { + assertEquals(levelsData, lm.getLevelsData(island)); + + } + + /** + * Test method for {@link world.bentobox.level.LevelsManager#formatLevel(long)}. + */ + @Test + public void testFormatLevel() { + assertEquals("123456789", lm.formatLevel(123456789L)); + when(settings.isShorthand()).thenReturn(true); + assertEquals("123.5M", lm.formatLevel(123456789L)); + assertEquals("1.2k", lm.formatLevel(1234L)); + assertEquals("123.5G", lm.formatLevel(123456789352L)); + assertEquals("1.2T", lm.formatLevel(1234567893524L)); + assertEquals("12345.7T", lm.formatLevel(12345678345345349L)); + + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#getTopTen(org.bukkit.World, int)}. + */ + @Test + public void testGetTopTenEmpty() { + Map tt = lm.getTopTen(world, Level.TEN); + assertTrue(tt.isEmpty()); + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#getTopTen(org.bukkit.World, int)}. + */ + @Test + public void testGetTopTen() { + testLoadTopTens(); + Map tt = lm.getTopTen(world, Level.TEN); + assertFalse(tt.isEmpty()); + assertEquals(1, tt.size()); + assertEquals(1, lm.getTopTen(world, 1).size()); + } + + /** * Test method for {@link world.bentobox.level.LevelsManager#getTopTen(org.bukkit.World, int)}. */ @Test public void testGetTopTenNoOwners() { - when(im.isOwner(eq(world), any())).thenReturn(false); + when(im.hasIsland(eq(world), any(UUID.class))).thenReturn(false); testLoadTopTens(); Map tt = lm.getTopTen(world, Level.TEN); assertTrue(tt.isEmpty()); } - /** - * Test method for {@link world.bentobox.level.LevelsManager#hasTopTenPerm(org.bukkit.World, java.util.UUID)}. - */ - @Test - public void testHasTopTenPerm() { - assertTrue(lm.hasTopTenPerm(world, uuid)); - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#loadTopTens()}. - */ - @Test - public void testLoadTopTens() { - ArgumentCaptor task = ArgumentCaptor.forClass(Runnable.class); - lm.loadTopTens(); - PowerMockito.verifyStatic(Bukkit.class); // 1 - Bukkit.getScheduler(); - verify(scheduler).runTaskAsynchronously(eq(plugin), task.capture()); - task.getValue().run(); - verify(addon).log("Generating rankings"); - verify(addon).log("Generated rankings for bskyblock-world"); - - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#removeEntry(org.bukkit.World, java.util.UUID)}. - */ - @Test - public void testRemoveEntry() { - testLoadTopTens(); - Map tt = lm.getTopTen(world, Level.TEN); - assertTrue(tt.containsKey(uuid)); - lm.removeEntry(world, uuid); - tt = lm.getTopTen(world, Level.TEN); - assertFalse(tt.containsKey(uuid)); - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#setInitialIslandLevel(world.bentobox.bentobox.database.objects.Island, long)}. - */ - @Test - public void testSetInitialIslandLevel() { - lm.setInitialIslandLevel(island, Level.TEN); - assertEquals(Level.TEN, lm.getInitialLevel(island)); - } - - /** - * Test method for {@link world.bentobox.level.LevelsManager#setIslandLevel(org.bukkit.World, java.util.UUID, long)}. - */ - @Test - public void testSetIslandLevel() { - lm.setIslandLevel(world, uuid, 1234); - assertEquals(1234, lm.getIslandLevel(world, uuid)); - - } - - - /** - * Test method for {@link world.bentobox.level.LevelsManager#getRank(World, UUID)} - */ - @Test - public void testGetRank() { - lm.createAndCleanRankings(world); - Map ttl = lm.getTopTenLists(); - Map tt = ttl.get(world).getTopTen(); - for (long i = 100; i < 150; i++) { - tt.put(UUID.randomUUID(), i); - } - // Put player as lowest rank - tt.put(uuid, 10L); - assertEquals(51, lm.getRank(world, uuid)); - // Put player as highest rank - tt.put(uuid, 1000L); - assertEquals(1, lm.getRank(world, uuid)); - // Unknown UUID - lowest rank + 1 - assertEquals(52, lm.getRank(world, UUID.randomUUID())); - } + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#hasTopTenPerm(org.bukkit.World, java.util.UUID)}. + */ + @Test + public void testHasTopTenPerm() { + assertTrue(lm.hasTopTenPerm(world, uuid)); + } + + /** + * Test method for {@link world.bentobox.level.LevelsManager#loadTopTens()}. + */ + @Test + public void testLoadTopTens() { + ArgumentCaptor task = ArgumentCaptor.forClass(Runnable.class); + lm.loadTopTens(); + PowerMockito.verifyStatic(Bukkit.class); // 1 + Bukkit.getScheduler(); + verify(scheduler).runTaskAsynchronously(eq(plugin), task.capture()); + task.getValue().run(); + verify(addon).log("Generating rankings"); + verify(addon).log("Generated rankings for bskyblock-world"); + + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#removeEntry(org.bukkit.World, java.util.UUID)}. + */ + @Test + public void testRemoveEntry() { + testLoadTopTens(); + Map tt = lm.getTopTen(world, Level.TEN); + assertTrue(tt.containsKey(uuid)); + lm.removeEntry(world, uuid); + tt = lm.getTopTen(world, Level.TEN); + assertFalse(tt.containsKey(uuid)); + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#setInitialIslandLevel(world.bentobox.bentobox.database.objects.Island, long)}. + */ + @Test + public void testSetInitialIslandLevel() { + lm.setInitialIslandLevel(island, Level.TEN); + assertEquals(Level.TEN, lm.getInitialLevel(island)); + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#setIslandLevel(org.bukkit.World, java.util.UUID, long)}. + */ + @Test + public void testSetIslandLevel() { + lm.setIslandLevel(world, uuid, 1234); + assertEquals(1234, lm.getIslandLevel(world, uuid)); + + } + + /** + * Test method for + * {@link world.bentobox.level.LevelsManager#getRank(World, UUID)} + */ + @Test + public void testGetRank() { + lm.createAndCleanRankings(world); + Map ttl = lm.getTopTenLists(); + Map tt = ttl.get(world).getTopTen(); + for (long i = 100; i < 150; i++) { + tt.put(UUID.randomUUID(), i); + } + // Put player as lowest rank + tt.put(uuid, 10L); + assertEquals(51, lm.getRank(world, uuid)); + // Put player as highest rank + tt.put(uuid, 1000L); + assertEquals(1, lm.getRank(world, uuid)); + // Unknown UUID - lowest rank + 1 + assertEquals(52, lm.getRank(world, UUID.randomUUID())); + } }