Implements the scrapper global edit command

Changes setting quite a bit to avoid code duplication
This commit is contained in:
Kristian Knarvik 2023-11-16 01:17:27 +01:00
parent f3f3f66c38
commit 4f885135e3
18 changed files with 716 additions and 791 deletions

View File

@ -3,15 +3,14 @@ package net.knarcraft.blacksmith.command.blacksmith;
import net.knarcraft.blacksmith.BlacksmithPlugin; import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.command.ReloadCommand; import net.knarcraft.blacksmith.command.ReloadCommand;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.config.blacksmith.BlacksmithNPCSetting; import net.knarcraft.blacksmith.config.blacksmith.BlacksmithSetting;
import net.knarcraft.blacksmith.config.blacksmith.GlobalBlacksmithSetting;
import net.knarcraft.blacksmith.config.blacksmith.GlobalBlacksmithSettings; import net.knarcraft.blacksmith.config.blacksmith.GlobalBlacksmithSettings;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage; import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.blacksmith.formatting.ItemType; import net.knarcraft.blacksmith.formatting.ItemType;
import net.knarcraft.blacksmith.util.ConfigCommandHelper;
import net.knarcraft.blacksmith.util.InputParsingHelper; import net.knarcraft.blacksmith.util.InputParsingHelper;
import net.knarcraft.blacksmith.util.ItemHelper; import net.knarcraft.blacksmith.util.ItemHelper;
import net.knarcraft.blacksmith.util.TypeValidationHelper; import net.knarcraft.blacksmith.util.TypeValidationHelper;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
@ -20,12 +19,8 @@ import org.bukkit.enchantments.Enchantment;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import static net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage.getValueChangedMessage;
/** /**
* The command used for changing global configuration options * The command used for changing global blacksmith configuration options
*/ */
public class BlackSmithConfigCommand implements CommandExecutor { public class BlackSmithConfigCommand implements CommandExecutor {
@ -42,124 +37,36 @@ public class BlackSmithConfigCommand implements CommandExecutor {
} }
GlobalBlacksmithSettings settings = BlacksmithPlugin.getInstance().getGlobalBlacksmithSettings(); GlobalBlacksmithSettings settings = BlacksmithPlugin.getInstance().getGlobalBlacksmithSettings();
//Find which global setting the user has specified, if any //Find which setting the user has specified, if any
GlobalBlacksmithSetting detectedGlobalBlacksmithSetting = null; BlacksmithSetting detectedSetting = BlacksmithSetting.getSetting(commandName);
for (GlobalBlacksmithSetting globalBlacksmithSetting : GlobalBlacksmithSetting.values()) { if (detectedSetting == null) {
if (commandName.equalsIgnoreCase(globalBlacksmithSetting.getCommandName())) { return false;
detectedGlobalBlacksmithSetting = globalBlacksmithSetting;
break;
}
}
//Find which npc setting the user has specified, if any
BlacksmithNPCSetting detectedBlacksmithNPCSetting = null;
for (BlacksmithNPCSetting blacksmithNpcSetting : BlacksmithNPCSetting.values()) {
if (commandName.equalsIgnoreCase(blacksmithNpcSetting.getCommandName())) {
detectedBlacksmithNPCSetting = blacksmithNpcSetting;
break;
}
} }
//Display the current value of a setting //Display the current value of a setting
if (args.length == 1) { if (args.length == 1) {
return displayCurrentValue(detectedGlobalBlacksmithSetting, detectedBlacksmithNPCSetting, settings, sender); ConfigCommandHelper.displayCurrentValue(detectedSetting, settings, sender);
return true;
} else if (args.length == 2 && isSpecialCase(commandName)) { } else if (args.length == 2 && isSpecialCase(commandName)) {
if (displaySpecialCaseValue(args[1], sender, detectedGlobalBlacksmithSetting, settings)) { if (displaySpecialCaseValue(args[1], sender, detectedSetting, settings)) {
return true; return true;
} }
} }
//Update the value of a special-case setting //Update the value of a special-case setting
if (args.length == 3 && updateSpecialCase(settings, detectedGlobalBlacksmithSetting, args, sender)) { if (args.length == 3 && updateSpecialCase(settings, detectedSetting, args, sender)) {
return true; return true;
} }
//Change the value of the specified setting //Change the value of the specified setting
if ((detectedGlobalBlacksmithSetting != null && if (TypeValidationHelper.isValid(detectedSetting.getValueType(), args[1], sender)) {
TypeValidationHelper.isValid(detectedGlobalBlacksmithSetting.getValueType(), args[1], sender)) || ConfigCommandHelper.changeValue(args, detectedSetting, settings, sender);
(detectedBlacksmithNPCSetting != null &&
TypeValidationHelper.isValid(detectedBlacksmithNPCSetting.getValueType(), args[1], sender))) {
return changeValue(args, detectedGlobalBlacksmithSetting, detectedBlacksmithNPCSetting, settings, sender);
} else {
return false;
}
}
/**
* Changes the value of the setting defined in the user's input
*
* @param args <p>The arguments given by the user</p>
* @param detectedGlobalBlacksmithSetting <p>The global setting recognized from the input, if any</p>
* @param detectedBlacksmithNPCSetting <p>The NPC setting recognized from the input, if any</p>
* @param settings <p>The global settings object to get settings from</p>
* @param sender <p>The command sender to display any output to</p>
* @return <p>True if the value was successfully changed</p>
*/
private boolean changeValue(@NotNull String[] args, @Nullable GlobalBlacksmithSetting detectedGlobalBlacksmithSetting,
@Nullable BlacksmithNPCSetting detectedBlacksmithNPCSetting,
@NotNull GlobalBlacksmithSettings settings, @NotNull CommandSender sender) {
String newValue = args[1];
if (detectedGlobalBlacksmithSetting != null) {
settings.changeValue(detectedGlobalBlacksmithSetting, newValue);
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
getValueChangedMessage(detectedGlobalBlacksmithSetting.getCommandName(), newValue));
return true;
} else if (detectedBlacksmithNPCSetting != null) {
//This makes sure all arguments are treated as a sentence
if (detectedBlacksmithNPCSetting.getValueType() == SettingValueType.STRING) {
newValue = String.join(" ", Arrays.asList(args).subList(1, args.length));
}
settings.changeValue(detectedBlacksmithNPCSetting, newValue);
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
getValueChangedMessage(detectedBlacksmithNPCSetting.getCommandName(), newValue));
return true; return true;
} else { } else {
return false; return false;
} }
} }
/**
* Displays the current value of the selected setting
*
* @param detectedGlobalBlacksmithSetting <p>The global setting recognized from the input, if any</p>
* @param detectedBlacksmithNPCSetting <p>The NPC setting recognized from the input, if any</p>
* @param settings <p>The global settings object to get settings from</p>
* @param sender <p>The command sender to display any output to</p>
* @return <p>True if a settings was successfully displayed</p>
*/
private boolean displayCurrentValue(@Nullable GlobalBlacksmithSetting detectedGlobalBlacksmithSetting,
@Nullable BlacksmithNPCSetting detectedBlacksmithNPCSetting,
@NotNull GlobalBlacksmithSettings settings, @NotNull CommandSender sender) {
String settingValue;
String correctCommandName;
boolean printRawValue = false;
//Find the value of the specified setting
//TODO: See if there's a way to remove this duplication
if (detectedGlobalBlacksmithSetting != null) {
settingValue = String.valueOf(settings.getRawValue(detectedGlobalBlacksmithSetting));
correctCommandName = detectedGlobalBlacksmithSetting.getCommandName();
} else if (detectedBlacksmithNPCSetting != null) {
settingValue = String.valueOf(settings.getRawValue(detectedBlacksmithNPCSetting));
correctCommandName = detectedBlacksmithNPCSetting.getCommandName();
//For messages, print an additional raw value showing which color codes are used
if (detectedBlacksmithNPCSetting.getPath().startsWith("defaults.messages")) {
printRawValue = true;
}
} else {
return false;
}
//Display the current value of the setting
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
BlacksmithTranslatableMessage.getCurrentValueMessage(correctCommandName, settingValue));
//Print the value with any colors displayed as &a-f0-9
if (printRawValue) {
sender.sendMessage(BlacksmithTranslatableMessage.getRawValueMessage(
settingValue.replace(ChatColor.COLOR_CHAR, '&')));
}
return true;
}
/** /**
* Displays the current value of a special-case configuration value * Displays the current value of a special-case configuration value
* *
@ -170,15 +77,15 @@ public class BlackSmithConfigCommand implements CommandExecutor {
* @return <p>True if the value was successfully displayed</p> * @return <p>True if the value was successfully displayed</p>
*/ */
private boolean displaySpecialCaseValue(@NotNull String selector, @NotNull CommandSender sender, private boolean displaySpecialCaseValue(@NotNull String selector, @NotNull CommandSender sender,
@Nullable GlobalBlacksmithSetting setting, @Nullable BlacksmithSetting setting,
@NotNull GlobalBlacksmithSettings settings) { @NotNull GlobalBlacksmithSettings settings) {
if (setting == GlobalBlacksmithSetting.BASE_PRICE || setting == GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT) { if (setting == BlacksmithSetting.BASE_PRICE || setting == BlacksmithSetting.PRICE_PER_DURABILITY_POINT) {
Material material = InputParsingHelper.matchMaterial(selector); Material material = InputParsingHelper.matchMaterial(selector);
if (material == null) { if (material == null) {
return false; return false;
} }
String currentValue; String currentValue;
if (setting == GlobalBlacksmithSetting.BASE_PRICE) { if (setting == BlacksmithSetting.BASE_PRICE) {
currentValue = String.valueOf(settings.getBasePrice(material)); currentValue = String.valueOf(settings.getBasePrice(material));
} else { } else {
currentValue = String.valueOf(settings.getPricePerDurabilityPoint(material)); currentValue = String.valueOf(settings.getPricePerDurabilityPoint(material));
@ -187,7 +94,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
BlacksmithTranslatableMessage.getItemCurrentValueMessage(setting.getCommandName(), BlacksmithTranslatableMessage.getItemCurrentValueMessage(setting.getCommandName(),
ItemType.MATERIAL, material.name(), currentValue)); ItemType.MATERIAL, material.name(), currentValue));
return true; return true;
} else if (setting == GlobalBlacksmithSetting.ENCHANTMENT_COST) { } else if (setting == BlacksmithSetting.ENCHANTMENT_COST) {
Enchantment enchantment = InputParsingHelper.matchEnchantment(selector); Enchantment enchantment = InputParsingHelper.matchEnchantment(selector);
if (enchantment == null) { if (enchantment == null) {
return false; return false;
@ -209,22 +116,22 @@ public class BlackSmithConfigCommand implements CommandExecutor {
* @return <p>True if the command is a special case</p> * @return <p>True if the command is a special case</p>
*/ */
private boolean isSpecialCase(@NotNull String commandName) { private boolean isSpecialCase(@NotNull String commandName) {
return commandName.equalsIgnoreCase(GlobalBlacksmithSetting.BASE_PRICE.getCommandName()) || return commandName.equalsIgnoreCase(BlacksmithSetting.BASE_PRICE.getCommandName()) ||
commandName.equalsIgnoreCase(GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT.getCommandName()) || commandName.equalsIgnoreCase(BlacksmithSetting.PRICE_PER_DURABILITY_POINT.getCommandName()) ||
commandName.equalsIgnoreCase(GlobalBlacksmithSetting.ENCHANTMENT_COST.getCommandName()); commandName.equalsIgnoreCase(BlacksmithSetting.ENCHANTMENT_COST.getCommandName());
} }
/** /**
* Updates a special-case configuration value if a special-case is encountered * Updates a special-case configuration value if a special-case is encountered
* *
* @param settings <p>The settings to modify</p> * @param settings <p>The settings to modify</p>
* @param detectedGlobalBlacksmithSetting <p>The global setting specified</p> * @param blacksmithSetting <p>The setting specified</p>
* @param args <p>All arguments given</p> * @param args <p>All arguments given</p>
* @param sender <p>The command sender to notify if successful</p> * @param sender <p>The command sender to notify if successful</p>
* @return <p>True if already handled as a special case</p> * @return <p>True if already handled as a special case</p>
*/ */
private boolean updateSpecialCase(@NotNull GlobalBlacksmithSettings settings, private boolean updateSpecialCase(@NotNull GlobalBlacksmithSettings settings,
@Nullable GlobalBlacksmithSetting detectedGlobalBlacksmithSetting, @Nullable BlacksmithSetting blacksmithSetting,
@NotNull String[] args, @NotNull String[] args,
CommandSender sender) { CommandSender sender) {
if (InputParsingHelper.isEmpty(args[2])) { if (InputParsingHelper.isEmpty(args[2])) {
@ -235,10 +142,10 @@ public class BlackSmithConfigCommand implements CommandExecutor {
double newPrice = Double.parseDouble(args[2]); double newPrice = Double.parseDouble(args[2]);
String newValue = String.valueOf(newPrice); String newValue = String.valueOf(newPrice);
if (detectedGlobalBlacksmithSetting == GlobalBlacksmithSetting.BASE_PRICE || if (blacksmithSetting == BlacksmithSetting.BASE_PRICE ||
detectedGlobalBlacksmithSetting == GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT) { blacksmithSetting == BlacksmithSetting.PRICE_PER_DURABILITY_POINT) {
return updatePriceSpecialCase(settings, detectedGlobalBlacksmithSetting, args[1], newPrice, sender); return updatePriceSpecialCase(settings, blacksmithSetting, args[1], newPrice, sender);
} else if (detectedGlobalBlacksmithSetting == GlobalBlacksmithSetting.ENCHANTMENT_COST) { } else if (blacksmithSetting == BlacksmithSetting.ENCHANTMENT_COST) {
//Update enchantment cost for an item //Update enchantment cost for an item
Enchantment enchantment = InputParsingHelper.matchEnchantment(args[1]); Enchantment enchantment = InputParsingHelper.matchEnchantment(args[1]);
if (enchantment == null) { if (enchantment == null) {
@ -248,7 +155,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
String itemChanged = enchantment.getKey().getKey(); String itemChanged = enchantment.getKey().getKey();
settings.setEnchantmentCost(enchantment, newPrice); settings.setEnchantmentCost(enchantment, newPrice);
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender, BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
BlacksmithTranslatableMessage.getItemValueChangedMessage(detectedGlobalBlacksmithSetting.getCommandName(), BlacksmithTranslatableMessage.getItemValueChangedMessage(blacksmithSetting.getCommandName(),
itemType, itemChanged, newValue)); itemType, itemChanged, newValue));
return true; return true;
} else { } else {
@ -260,14 +167,14 @@ public class BlackSmithConfigCommand implements CommandExecutor {
* Updates a special case price configuration value if a special case is encountered * Updates a special case price configuration value if a special case is encountered
* *
* @param settings <p>The settings to modify</p> * @param settings <p>The settings to modify</p>
* @param detectedGlobalBlacksmithSetting <p>The global setting specified</p> * @param blacksmithSetting <p>The setting specified</p>
* @param materialName <p>The material name to update the price for</p> * @param materialName <p>The material name to update the price for</p>
* @param newPrice <p>The new price to update to</p> * @param newPrice <p>The new price to update to</p>
* @param sender <p>The command sender to respond to</p> * @param sender <p>The command sender to respond to</p>
* @return <p>True if the input was valid, and the item(s) was/were updated</p> * @return <p>True if the input was valid, and the item(s) was/were updated</p>
*/ */
private boolean updatePriceSpecialCase(@NotNull GlobalBlacksmithSettings settings, private boolean updatePriceSpecialCase(@NotNull GlobalBlacksmithSettings settings,
@NotNull GlobalBlacksmithSetting detectedGlobalBlacksmithSetting, @NotNull BlacksmithSetting blacksmithSetting,
@NotNull String materialName, double newPrice, @NotNull String materialName, double newPrice,
@NotNull CommandSender sender) { @NotNull CommandSender sender) {
ItemType itemType = ItemType.MATERIAL; ItemType itemType = ItemType.MATERIAL;
@ -275,14 +182,14 @@ public class BlackSmithConfigCommand implements CommandExecutor {
//Update base price or price per durability point for an item //Update base price or price per durability point for an item
if (materialName.contains("*")) { if (materialName.contains("*")) {
itemChanged = materialName; itemChanged = materialName;
updateAllMatchedPrices(settings, detectedGlobalBlacksmithSetting, materialName, newPrice); updateAllMatchedPrices(settings, blacksmithSetting, materialName, newPrice);
} else { } else {
Material material = InputParsingHelper.matchMaterial(materialName); Material material = InputParsingHelper.matchMaterial(materialName);
if (material == null) { if (material == null) {
return false; return false;
} }
itemChanged = material.name(); itemChanged = material.name();
if (detectedGlobalBlacksmithSetting == GlobalBlacksmithSetting.BASE_PRICE) { if (blacksmithSetting == BlacksmithSetting.BASE_PRICE) {
settings.setBasePrice(material, newPrice); settings.setBasePrice(material, newPrice);
} else { } else {
settings.setPricePerDurabilityPoint(material, newPrice); settings.setPricePerDurabilityPoint(material, newPrice);
@ -290,7 +197,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
} }
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender, BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
BlacksmithTranslatableMessage.getItemValueChangedMessage(detectedGlobalBlacksmithSetting.getCommandName(), BlacksmithTranslatableMessage.getItemValueChangedMessage(blacksmithSetting.getCommandName(),
itemType, itemChanged, String.valueOf(newPrice))); itemType, itemChanged, String.valueOf(newPrice)));
return true; return true;
} }
@ -299,12 +206,12 @@ public class BlackSmithConfigCommand implements CommandExecutor {
* Updates all materials matching the material name wildcard * Updates all materials matching the material name wildcard
* *
* @param settings <p>The settings to modify</p> * @param settings <p>The settings to modify</p>
* @param detectedGlobalBlacksmithSetting <p>The global setting specified</p> * @param blacksmithSetting <p>The setting specified</p>
* @param materialName <p>The wildcard material name to update cost for</p> * @param materialName <p>The wildcard material name to update cost for</p>
* @param newPrice <p>The new cost for the matched items</p> * @param newPrice <p>The new cost for the matched items</p>
*/ */
private void updateAllMatchedPrices(@NotNull GlobalBlacksmithSettings settings, private void updateAllMatchedPrices(@NotNull GlobalBlacksmithSettings settings,
@NotNull GlobalBlacksmithSetting detectedGlobalBlacksmithSetting, @NotNull BlacksmithSetting blacksmithSetting,
@NotNull String materialName, double newPrice) { @NotNull String materialName, double newPrice) {
String search = InputParsingHelper.regExIfy(materialName); String search = InputParsingHelper.regExIfy(materialName);
for (Material material : ItemHelper.getAllReforgeAbleMaterials()) { for (Material material : ItemHelper.getAllReforgeAbleMaterials()) {
@ -312,7 +219,7 @@ public class BlackSmithConfigCommand implements CommandExecutor {
continue; continue;
} }
if (detectedGlobalBlacksmithSetting == GlobalBlacksmithSetting.BASE_PRICE) { if (blacksmithSetting == BlacksmithSetting.BASE_PRICE) {
settings.setBasePrice(material, newPrice); settings.setBasePrice(material, newPrice);
} else { } else {
settings.setPricePerDurabilityPoint(material, newPrice); settings.setPricePerDurabilityPoint(material, newPrice);

View File

@ -1,8 +1,7 @@
package net.knarcraft.blacksmith.command.blacksmith; package net.knarcraft.blacksmith.command.blacksmith;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.config.blacksmith.BlacksmithNPCSetting; import net.knarcraft.blacksmith.config.blacksmith.BlacksmithSetting;
import net.knarcraft.blacksmith.config.blacksmith.GlobalBlacksmithSetting;
import net.knarcraft.blacksmith.util.InputParsingHelper; import net.knarcraft.blacksmith.util.InputParsingHelper;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -17,7 +16,7 @@ import static net.knarcraft.blacksmith.util.TabCompleteValuesHelper.getTabComple
import static net.knarcraft.knarlib.util.TabCompletionHelper.filterMatchingContains; import static net.knarcraft.knarlib.util.TabCompletionHelper.filterMatchingContains;
/** /**
* The tab completer for the command used for changing global configuration options * The tab completer for the command used for changing global blacksmith configuration options
*/ */
public class BlackSmithConfigTabCompleter implements TabCompleter { public class BlackSmithConfigTabCompleter implements TabCompleter {
@ -32,72 +31,61 @@ public class BlackSmithConfigTabCompleter implements TabCompleter {
//Arguments: <setting> [new value/material or enchantment] [] //Arguments: <setting> [new value/material or enchantment] []
//Prevent tab-completion when typing messages with spaces //Prevent tab-completion when typing messages with spaces
if (skipCompletionForSpacedMessage(args) != null) { if (args.length > 2 && skipCompletionForSpacedMessage(args[0]) != null) {
return new ArrayList<>(); return new ArrayList<>();
} }
if (args.length == 1) { if (args.length == 1) {
List<String> availableCommands = new ArrayList<>(); List<String> availableCommands = new ArrayList<>();
availableCommands.add("reload"); availableCommands.add("reload");
for (BlacksmithNPCSetting setting : BlacksmithNPCSetting.values()) { for (BlacksmithSetting setting : BlacksmithSetting.values()) {
availableCommands.add(setting.getCommandName()); availableCommands.add(setting.getCommandName());
} }
for (GlobalBlacksmithSetting globalBlacksmithSetting : GlobalBlacksmithSetting.values()) {
availableCommands.add(globalBlacksmithSetting.getCommandName());
}
return filterMatchingContains(availableCommands, args[0]); return filterMatchingContains(availableCommands, args[0]);
} else if (args.length == 2) { } else if (args.length == 2) {
return tabCompleteCommandValues(args[0], args[1]); return tabCompleteCommandValues(args[0], args[1]);
} else if (args.length == 3) { } else if (args.length == 3) {
//Get per-material tab completions, or return nothing if an invalid setting was specified //Get per-material tab completions, or return nothing if an invalid setting was specified
for (GlobalBlacksmithSetting globalBlacksmithSetting : GlobalBlacksmithSetting.values()) { BlacksmithSetting blacksmithSetting = BlacksmithSetting.getSetting(args[0]);
if (globalBlacksmithSetting.getCommandName().equalsIgnoreCase(args[0])) { if (blacksmithSetting != null) {
return getPerTypeTabCompletions(globalBlacksmithSetting, args); return getPerTypeTabCompletions(blacksmithSetting, args);
} } else {
}
return new ArrayList<>(); return new ArrayList<>();
} }
}
return null; return null;
} }
/** /**
* Checks whether to tab-complete nothing because a message containing spaces is being written * Checks whether to tab-complete nothing because a message containing spaces is being written
* *
* @param args <p>The arguments given by the user</p> * @param command <p>The command specified by the user</p>
* @return <p>Null if not writing a spaced message</p> * @return <p>Null if not writing a spaced message</p>
*/ */
private List<String> skipCompletionForSpacedMessage(@NotNull String[] args) { private List<String> skipCompletionForSpacedMessage(@NotNull String command) {
if (args.length > 2) { BlacksmithSetting blacksmithSetting = BlacksmithSetting.getSetting(command);
BlacksmithNPCSetting blacksmithNpcSetting = null; if (blacksmithSetting != null && blacksmithSetting.isMessage()) {
for (BlacksmithNPCSetting setting : BlacksmithNPCSetting.values()) {
if (setting.getCommandName().equalsIgnoreCase(args[0])) {
blacksmithNpcSetting = setting;
break;
}
}
if (blacksmithNpcSetting != null && blacksmithNpcSetting.getPath().startsWith("defaults.messages")) {
return new ArrayList<>(); return new ArrayList<>();
} }
}
return null; return null;
} }
/** /**
* Gets tab-completions for a selected material or enchantment * Gets tab-completions for a selected material or enchantment
* *
* @param globalBlacksmithSetting <p>The global setting to get tab-completions for</p> * @param blacksmithSetting <p>The global setting to get tab-completions for</p>
* @param args <p>The arguments given by the user</p> * @param args <p>The arguments given by the user</p>
* @return <p>The tab-completions to show to the user</p> * @return <p>The tab-completions to show to the user</p>
*/ */
private List<String> getPerTypeTabCompletions(@NotNull GlobalBlacksmithSetting globalBlacksmithSetting, private List<String> getPerTypeTabCompletions(@NotNull BlacksmithSetting blacksmithSetting,
@NotNull String[] args) { @NotNull String[] args) {
//Display possible tab-completions only if a valid enchantment or material is provided //Display possible tab-completions only if a valid enchantment or material is provided
if (((globalBlacksmithSetting == GlobalBlacksmithSetting.BASE_PRICE || if (((blacksmithSetting == BlacksmithSetting.BASE_PRICE ||
globalBlacksmithSetting == GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT) && blacksmithSetting == BlacksmithSetting.PRICE_PER_DURABILITY_POINT) &&
InputParsingHelper.matchMaterial(args[1]) != null) || InputParsingHelper.matchMaterial(args[1]) != null) ||
(globalBlacksmithSetting == GlobalBlacksmithSetting.ENCHANTMENT_COST && (blacksmithSetting == BlacksmithSetting.ENCHANTMENT_COST &&
InputParsingHelper.matchEnchantment(args[1]) != null)) { InputParsingHelper.matchEnchantment(args[1]) != null)) {
return filterMatchingContains(getTabCompletions(globalBlacksmithSetting.getValueType()), args[2]); return filterMatchingContains(getTabCompletions(blacksmithSetting.getValueType()), args[2]);
} else { } else {
return new ArrayList<>(); return new ArrayList<>();
} }
@ -114,35 +102,29 @@ public class BlackSmithConfigTabCompleter implements TabCompleter {
if (commandName.equalsIgnoreCase("reload")) { if (commandName.equalsIgnoreCase("reload")) {
return new ArrayList<>(); return new ArrayList<>();
} }
for (GlobalBlacksmithSetting globalBlacksmithSetting : GlobalBlacksmithSetting.values()) { BlacksmithSetting setting = BlacksmithSetting.getSetting(commandName);
if (globalBlacksmithSetting.getCommandName().equalsIgnoreCase(commandName)) { if (setting != null) {
return getCompletions(globalBlacksmithSetting, commandValue); return getCompletions(setting, commandValue);
} } else {
}
for (BlacksmithNPCSetting blacksmithNpcSetting : BlacksmithNPCSetting.values()) {
if (blacksmithNpcSetting.getCommandName().equalsIgnoreCase(commandName)) {
return filterMatchingContains(getTabCompletions(
blacksmithNpcSetting.getValueType()), commandValue);
}
}
return null; return null;
} }
}
/** /**
* Gets tab-completions for the given global setting and filters on the command value * Gets tab-completions for the given global setting and filters on the command value
* *
* @param globalBlacksmithSetting <p>The global setting to get tab-completions for</p> * @param blacksmithSetting <p>The global setting to get tab-completions for</p>
* @param commandValue <p>The command value used to filter between available tab-completions</p> * @param commandValue <p>The command value used to filter between available tab-completions</p>
* @return <p>The available tab-completions</p> * @return <p>The available tab-completions</p>
*/ */
private List<String> getCompletions(@NotNull GlobalBlacksmithSetting globalBlacksmithSetting, private List<String> getCompletions(@NotNull BlacksmithSetting blacksmithSetting,
@NotNull String commandValue) { @NotNull String commandValue) {
List<String> returnValues = filterMatchingContains( List<String> returnValues = filterMatchingContains(
getTabCompletions(globalBlacksmithSetting.getValueType()), commandValue); getTabCompletions(blacksmithSetting.getValueType()), commandValue);
if (globalBlacksmithSetting == GlobalBlacksmithSetting.BASE_PRICE || if (blacksmithSetting == BlacksmithSetting.BASE_PRICE ||
globalBlacksmithSetting == GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT) { blacksmithSetting == BlacksmithSetting.PRICE_PER_DURABILITY_POINT) {
returnValues.addAll(filterMatchingContains(getTabCompletions(SettingValueType.MATERIAL), commandValue)); returnValues.addAll(filterMatchingContains(getTabCompletions(SettingValueType.MATERIAL), commandValue));
} else if (globalBlacksmithSetting == GlobalBlacksmithSetting.ENCHANTMENT_COST) { } else if (blacksmithSetting == BlacksmithSetting.ENCHANTMENT_COST) {
returnValues.addAll(filterMatchingContains(getTabCompletions(SettingValueType.ENCHANTMENT), commandValue)); returnValues.addAll(filterMatchingContains(getTabCompletions(SettingValueType.ENCHANTMENT), commandValue));
} }
return returnValues; return returnValues;

View File

@ -4,7 +4,7 @@ import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC; import net.citizensnpcs.api.npc.NPC;
import net.knarcraft.blacksmith.BlacksmithPlugin; import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.config.blacksmith.BlacksmithNPCSetting; import net.knarcraft.blacksmith.config.blacksmith.BlacksmithSetting;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage; import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.knarcraft.blacksmith.trait.BlacksmithTrait; import net.knarcraft.blacksmith.trait.BlacksmithTrait;
import net.knarcraft.blacksmith.util.InputParsingHelper; import net.knarcraft.blacksmith.util.InputParsingHelper;
@ -42,43 +42,42 @@ public class BlackSmithEditCommand implements CommandExecutor {
BlacksmithTrait blacksmithTrait = npc.getTraitNullable(BlacksmithTrait.class); BlacksmithTrait blacksmithTrait = npc.getTraitNullable(BlacksmithTrait.class);
for (BlacksmithNPCSetting blacksmithNpcSetting : BlacksmithNPCSetting.values()) { BlacksmithSetting setting = BlacksmithSetting.getSetting(args[0]);
String commandName = blacksmithNpcSetting.getCommandName(); if (setting != null) {
if (commandName.equalsIgnoreCase(args[0])) {
String newValue = args.length < 2 ? null : args[1]; String newValue = args.length < 2 ? null : args[1];
//This makes sure all arguments are treated as a sentence //This makes sure all arguments are treated as a sentence
if (blacksmithNpcSetting.getValueType() == SettingValueType.STRING && args.length > 2) { if (setting.getValueType() == SettingValueType.STRING && args.length > 2) {
newValue = String.join(" ", Arrays.asList(args).subList(1, args.length)); newValue = String.join(" ", Arrays.asList(args).subList(1, args.length));
} }
return displayOrChangeNPCSetting(blacksmithTrait, blacksmithNpcSetting, newValue, sender); return displayOrChangeNPCSetting(blacksmithTrait, setting, newValue, sender);
} } else {
}
return false; return false;
} }
}
/** /**
* Changes the given NPC setting, or displays the current value if a new value isn't specified * Changes the given NPC setting, or displays the current value if a new value isn't specified
* *
* @param blacksmithTrait <p>The blacksmith trait belonging to the selected NPC</p> * @param blacksmithTrait <p>The blacksmith trait belonging to the selected NPC</p>
* @param blacksmithNpcSetting <p>The NPC setting to change</p> * @param blacksmithSetting <p>The NPC setting to change</p>
* @param newValue <p>The value to change the setting to</p> * @param newValue <p>The value to change the setting to</p>
* @param sender <p>The command sender to notify about results</p> * @param sender <p>The command sender to notify about results</p>
* @return <p>True if everything went successfully</p> * @return <p>True if everything went successfully</p>
*/ */
private boolean displayOrChangeNPCSetting(@NotNull BlacksmithTrait blacksmithTrait, private boolean displayOrChangeNPCSetting(@NotNull BlacksmithTrait blacksmithTrait,
@NotNull BlacksmithNPCSetting blacksmithNpcSetting, @NotNull BlacksmithSetting blacksmithSetting,
@Nullable String newValue, @Nullable String newValue,
@NotNull CommandSender sender) { @NotNull CommandSender sender) {
if (newValue == null) { if (newValue == null) {
//Display the current value of the setting //Display the current value of the setting
displayNPCSetting(blacksmithTrait, blacksmithNpcSetting, sender); displayNPCSetting(blacksmithTrait, blacksmithSetting, sender);
} else { } else {
//If an empty value or null, clear the value instead of changing it //If an empty value or null, clear the value instead of changing it
if (InputParsingHelper.isEmpty(newValue)) { if (InputParsingHelper.isEmpty(newValue)) {
newValue = null; newValue = null;
} else { } else {
//Abort if an invalid value is given //Abort if an invalid value is given
boolean isValidType = TypeValidationHelper.isValid(blacksmithNpcSetting.getValueType(), newValue, sender); boolean isValidType = TypeValidationHelper.isValid(blacksmithSetting.getValueType(), newValue, sender);
if (!isValidType) { if (!isValidType) {
return false; return false;
} }
@ -86,9 +85,9 @@ public class BlackSmithEditCommand implements CommandExecutor {
} }
//Change the setting //Change the setting
blacksmithTrait.getSettings().changeSetting(blacksmithNpcSetting, newValue); blacksmithTrait.getSettings().changeValue(blacksmithSetting, newValue);
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender, BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
getValueChangedMessage(blacksmithNpcSetting.getCommandName(), String.valueOf(newValue))); getValueChangedMessage(blacksmithSetting.getCommandName(), String.valueOf(newValue)));
//Save the changes immediately to prevent data loss on server crash //Save the changes immediately to prevent data loss on server crash
CitizensAPI.getNPCRegistry().saveToStore(); CitizensAPI.getNPCRegistry().saveToStore();
} }
@ -99,26 +98,26 @@ public class BlackSmithEditCommand implements CommandExecutor {
* Displays the current value of the given NPC setting * Displays the current value of the given NPC setting
* *
* @param blacksmithTrait <p>The blacksmith trait of the NPC to get the value from</p> * @param blacksmithTrait <p>The blacksmith trait of the NPC to get the value from</p>
* @param blacksmithNpcSetting <p>The NPC setting to see the value of</p> * @param blacksmithSetting <p>The NPC setting to see the value of</p>
* @param sender <p>The command sender to display the value to</p> * @param sender <p>The command sender to display the value to</p>
*/ */
private void displayNPCSetting(@NotNull BlacksmithTrait blacksmithTrait, private void displayNPCSetting(@NotNull BlacksmithTrait blacksmithTrait,
@NotNull BlacksmithNPCSetting blacksmithNpcSetting, @NotNull CommandSender sender) { @NotNull BlacksmithSetting blacksmithSetting, @NotNull CommandSender sender) {
String rawValue = String.valueOf(blacksmithTrait.getSettings().getRawValue(blacksmithNpcSetting)); String rawValue = String.valueOf(blacksmithTrait.getSettings().getRawValue(blacksmithSetting));
if (InputParsingHelper.isEmpty(rawValue)) { if (InputParsingHelper.isEmpty(rawValue)) {
//Display the default value, if no custom value has been specified //Display the default value, if no custom value has been specified
rawValue = String.valueOf(BlacksmithPlugin.getInstance().getGlobalBlacksmithSettings().getRawValue( rawValue = String.valueOf(BlacksmithPlugin.getInstance().getGlobalBlacksmithSettings().getRawValue(
blacksmithNpcSetting)); blacksmithSetting));
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender, BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
getCurrentValueMessage(blacksmithNpcSetting.getCommandName(), rawValue)); getCurrentValueMessage(blacksmithSetting.getCommandName(), rawValue));
} else { } else {
//Add a marker if the value has been customized //Add a marker if the value has been customized
String marker = BlacksmithPlugin.getTranslator().getTranslatedMessage( String marker = BlacksmithPlugin.getTranslator().getTranslatedMessage(
BlacksmithTranslatableMessage.SETTING_OVERRIDDEN_MARKER); BlacksmithTranslatableMessage.SETTING_OVERRIDDEN_MARKER);
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender, BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
getCurrentValueMessage(blacksmithNpcSetting.getCommandName(), rawValue) + marker); getCurrentValueMessage(blacksmithSetting.getCommandName(), rawValue) + marker);
} }
if (blacksmithNpcSetting.getPath().startsWith("defaults.messages")) { if (blacksmithSetting.getPath().startsWith("defaults.messages")) {
sender.sendMessage(BlacksmithTranslatableMessage.getRawValueMessage( sender.sendMessage(BlacksmithTranslatableMessage.getRawValueMessage(
rawValue.replace(ChatColor.COLOR_CHAR, '&'))); rawValue.replace(ChatColor.COLOR_CHAR, '&')));
} }

View File

@ -1,6 +1,6 @@
package net.knarcraft.blacksmith.command.blacksmith; package net.knarcraft.blacksmith.command.blacksmith;
import net.knarcraft.blacksmith.config.blacksmith.BlacksmithNPCSetting; import net.knarcraft.blacksmith.config.blacksmith.BlacksmithSetting;
import net.knarcraft.blacksmith.util.TabCompleteValuesHelper; import net.knarcraft.blacksmith.util.TabCompleteValuesHelper;
import net.knarcraft.knarlib.util.TabCompletionHelper; import net.knarcraft.knarlib.util.TabCompletionHelper;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -25,9 +25,11 @@ public class BlackSmithEditTabCompleter implements TabCompleter {
} }
List<String> npcSettings = new ArrayList<>(); List<String> npcSettings = new ArrayList<>();
for (BlacksmithNPCSetting setting : BlacksmithNPCSetting.values()) { for (BlacksmithSetting setting : BlacksmithSetting.values()) {
if (setting.isPerNPC()) {
npcSettings.add(setting.getCommandName()); npcSettings.add(setting.getCommandName());
} }
}
if (args.length == 1) { if (args.length == 1) {
return TabCompletionHelper.filterMatchingContains(npcSettings, args[0]); return TabCompletionHelper.filterMatchingContains(npcSettings, args[0]);
@ -48,13 +50,13 @@ public class BlackSmithEditTabCompleter implements TabCompleter {
* @return <p>Some valid options for the command's argument</p> * @return <p>Some valid options for the command's argument</p>
*/ */
private @Nullable List<String> tabCompleteCommandValues(@NotNull String commandName, @NotNull String commandValue) { private @Nullable List<String> tabCompleteCommandValues(@NotNull String commandName, @NotNull String commandValue) {
for (BlacksmithNPCSetting blacksmithNpcSetting : BlacksmithNPCSetting.values()) { BlacksmithSetting setting = BlacksmithSetting.getSetting(commandName);
if (blacksmithNpcSetting.getCommandName().equalsIgnoreCase(commandName)) { if (setting != null) {
return TabCompletionHelper.filterMatchingContains(TabCompleteValuesHelper.getTabCompletions( return TabCompletionHelper.filterMatchingContains(TabCompleteValuesHelper.getTabCompletions(
blacksmithNpcSetting.getValueType()), commandValue); setting.getValueType()), commandValue);
} } else {
}
return null; return null;
} }
}
} }

View File

@ -1,17 +1,53 @@
package net.knarcraft.blacksmith.command.scrapper; package net.knarcraft.blacksmith.command.scrapper;
import org.apache.commons.lang.NotImplementedException; import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.command.ReloadCommand;
import net.knarcraft.blacksmith.config.scrapper.GlobalScrapperSettings;
import net.knarcraft.blacksmith.config.scrapper.ScrapperSetting;
import net.knarcraft.blacksmith.util.ConfigCommandHelper;
import net.knarcraft.blacksmith.util.TypeValidationHelper;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/**
* The command used for changing global scrapper configuration options
*/
public class ScrapperConfigCommand implements CommandExecutor { public class ScrapperConfigCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label,
@NotNull String[] strings) { @NotNull String[] args) {
throw new NotImplementedException(); if (args.length == 0) {
return false;
}
String commandName = args[0];
if (commandName.equalsIgnoreCase("reload")) {
return new ReloadCommand().onCommand(sender, command, label, args);
}
GlobalScrapperSettings settings = BlacksmithPlugin.getInstance().getGlobalScrapperSettings();
//Find which setting the user has specified, if any
ScrapperSetting detectedSetting = ScrapperSetting.getSetting(commandName);
if (detectedSetting == null) {
return false;
}
//Display the current value of a setting
if (args.length == 1) {
ConfigCommandHelper.displayCurrentValue(detectedSetting, settings, sender);
return true;
}
//Change the value of the specified setting
if (TypeValidationHelper.isValid(detectedSetting.getValueType(), args[1], sender)) {
ConfigCommandHelper.changeValue(args, detectedSetting, settings, sender);
return true;
} else {
return false;
}
} }
} }

View File

@ -1,20 +1,79 @@
package net.knarcraft.blacksmith.command.scrapper; package net.knarcraft.blacksmith.command.scrapper;
import org.apache.commons.lang.NotImplementedException; import net.knarcraft.blacksmith.config.Setting;
import net.knarcraft.blacksmith.config.scrapper.ScrapperSetting;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter; import org.bukkit.command.TabCompleter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import static net.knarcraft.blacksmith.util.TabCompleteValuesHelper.getTabCompletions;
import static net.knarcraft.knarlib.util.TabCompletionHelper.filterMatchingContains;
/**
* The tab completer for the command used for changing global scrapper configuration options
*/
public class ScrapperConfigTabCompleter implements TabCompleter { public class ScrapperConfigTabCompleter implements TabCompleter {
@Override @Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command,
@NotNull String s, @NotNull String[] strings) { @NotNull String s, @NotNull String[] args) {
throw new NotImplementedException(); if (!sender.hasPermission("blacksmith.admin")) {
return new ArrayList<>();
}
//Arguments: <setting> [new value/material or enchantment] []
//Prevent tab-completion when typing messages with spaces
if (args.length > 2 && skipCompletionForSpacedMessage(args[0])) {
return new ArrayList<>();
}
if (args.length == 1) {
List<String> availableCommands = new ArrayList<>();
availableCommands.add("reload");
for (Setting setting : ScrapperSetting.values()) {
availableCommands.add(setting.getCommandName());
}
return filterMatchingContains(availableCommands, args[0]);
} else if (args.length == 2) {
return tabCompleteCommandValues(args[0], args[1]);
}
return null;
}
/**
* Checks whether to tab-complete nothing because a message containing spaces is being written
*
* @param command <p>The command specified by the user</p>
* @return <p>Null if not writing a spaced message</p>
*/
private boolean skipCompletionForSpacedMessage(@NotNull String command) {
Setting scrapperSetting = ScrapperSetting.getSetting(command);
return scrapperSetting != null && scrapperSetting.isMessage();
}
/**
* Tab completes the values available for the given command
*
* @param commandName <p>The name of the used command</p>
* @param commandValue <p>The command value used to filter tab-completions</p>
* @return <p>Some valid options for the command's argument</p>
*/
private List<String> tabCompleteCommandValues(@NotNull String commandName, @NotNull String commandValue) {
if (commandName.equalsIgnoreCase("reload")) {
return new ArrayList<>();
}
Setting scrapperSetting = ScrapperSetting.getSetting(commandName);
if (scrapperSetting != null) {
return filterMatchingContains(getTabCompletions(scrapperSetting.getValueType()), commandValue);
} else {
return null;
}
} }
} }

View File

@ -1,45 +0,0 @@
package net.knarcraft.blacksmith.config;
import org.jetbrains.annotations.NotNull;
/**
* An interface describing a global setting
*/
public interface GlobalSetting {
/**
* Gets the full config path for this setting
*
* @return <p>The full config path for this setting</p>
*/
@NotNull String getPath();
/**
* Gets the parent item of the defined path
*
* @return <p>The parent node</p>
*/
@NotNull String getParent();
/**
* Gets the value of this setting
*
* @return <p>The value of this setting</p>
*/
@NotNull Object getDefaultValue();
/**
* The name of the command used to change this setting
*
* @return <p>The name of this setting's command</p>
*/
@NotNull String getCommandName();
/**
* Gets the value type for this setting
*
* @return <p>The value type for this setting</p>
*/
@NotNull SettingValueType getValueType();
}

View File

@ -3,9 +3,9 @@ package net.knarcraft.blacksmith.config;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* An interface describing an NPC setting * An interface describing a setting
*/ */
public interface NPCSetting { public interface Setting {
/** /**
* Gets the full config path for this setting * Gets the full config path for this setting
@ -42,4 +42,20 @@ public interface NPCSetting {
*/ */
@NotNull SettingValueType getValueType(); @NotNull SettingValueType getValueType();
/**
* Gets whether this setting can be set per-NPC, or if it's set globally
*
* @return <p>True if this setting is set per-NPC</p>
*/
boolean isPerNPC();
/**
* Gets whether this setting is a customizable message
*
* <p>Messages are a special case, as you generally want to see the raw formatting, not just the result.</p>
*
* @return <p>True if this setting is a customizable message</p>
*/
boolean isMessage();
} }

View File

@ -0,0 +1,26 @@
package net.knarcraft.blacksmith.config;
/**
* An interface describing an object for managing settings
*
* @param <K> <p>The type of setting managed</p>
*/
public interface Settings<K extends Setting> {
/**
* Changes the value of the given setting
*
* @param setting <p>The setting to change</p>
* @param newValue <p>The new value of the setting</p>
*/
void changeValue(K setting, Object newValue);
/**
* Gets the current raw value of the given global setting
*
* @param setting <p>The setting to get</p>
* @return <p>The current raw setting value</p>
*/
Object getRawValue(K setting);
}

View File

@ -3,6 +3,7 @@ package net.knarcraft.blacksmith.config.blacksmith;
import net.citizensnpcs.api.util.DataKey; import net.citizensnpcs.api.util.DataKey;
import net.knarcraft.blacksmith.BlacksmithPlugin; import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.config.Settings;
import net.knarcraft.blacksmith.config.SmithPreset; import net.knarcraft.blacksmith.config.SmithPreset;
import net.knarcraft.blacksmith.config.TraitSettings; import net.knarcraft.blacksmith.config.TraitSettings;
import net.knarcraft.blacksmith.util.ConfigHelper; import net.knarcraft.blacksmith.util.ConfigHelper;
@ -23,11 +24,11 @@ import java.util.logging.Level;
/** /**
* A class which keeps track of all Blacksmith settings/config values for one NPC * A class which keeps track of all Blacksmith settings/config values for one NPC
*/ */
public class BlacksmithNPCSettings implements TraitSettings { public class BlacksmithNPCSettings implements TraitSettings, Settings<BlacksmithSetting> {
private final List<Material> reforgeAbleItems = new ArrayList<>(); private final List<Material> reforgeAbleItems = new ArrayList<>();
private final List<Enchantment> enchantmentBlocklist = new ArrayList<>(); private final List<Enchantment> enchantmentBlocklist = new ArrayList<>();
private final Map<BlacksmithNPCSetting, Object> currentValues = new HashMap<>(); private final Map<BlacksmithSetting, Object> currentValues = new HashMap<>();
private final GlobalBlacksmithSettings globalBlacksmithSettings; private final GlobalBlacksmithSettings globalBlacksmithSettings;
/** /**
@ -43,7 +44,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @param key <p>The data key to load variables from</p> * @param key <p>The data key to load variables from</p>
*/ */
public void loadVariables(DataKey key) { public void loadVariables(DataKey key) {
for (BlacksmithNPCSetting setting : BlacksmithNPCSetting.values()) { for (BlacksmithSetting setting : BlacksmithSetting.values()) {
if (key.keyExists(setting.getChildPath())) { if (key.keyExists(setting.getChildPath())) {
currentValues.put(setting, key.getRaw(setting.getChildPath())); currentValues.put(setting, key.getRaw(setting.getChildPath()));
} }
@ -59,18 +60,13 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @param key <p>The data key to save variables to</p> * @param key <p>The data key to save variables to</p>
*/ */
public void saveVariables(DataKey key) { public void saveVariables(DataKey key) {
for (BlacksmithNPCSetting setting : BlacksmithNPCSetting.values()) { for (BlacksmithSetting setting : BlacksmithSetting.values()) {
key.setRaw(setting.getChildPath(), currentValues.get(setting)); key.setRaw(setting.getChildPath(), currentValues.get(setting));
} }
} }
/** @Override
* Changes one setting to the given value public void changeValue(BlacksmithSetting setting, Object newValue) {
*
* @param setting <p>The setting to change</p>
* @param newValue <p>The new value of the setting</p>
*/
public void changeSetting(BlacksmithNPCSetting setting, Object newValue) {
if (setting.getValueType() == SettingValueType.STRING_LIST || if (setting.getValueType() == SettingValueType.STRING_LIST ||
setting.getValueType() == SettingValueType.REFORGE_ABLE_ITEMS) { setting.getValueType() == SettingValueType.REFORGE_ABLE_ITEMS) {
//Workaround to make sure it's treated as the correct type //Workaround to make sure it's treated as the correct type
@ -78,10 +74,10 @@ public class BlacksmithNPCSettings implements TraitSettings {
} else { } else {
currentValues.put(setting, newValue); currentValues.put(setting, newValue);
} }
if (setting == BlacksmithNPCSetting.REFORGE_ABLE_ITEMS) { if (setting == BlacksmithSetting.REFORGE_ABLE_ITEMS) {
updateReforgeAbleItems(); updateReforgeAbleItems();
} }
if (setting == BlacksmithNPCSetting.ENCHANTMENT_BLOCKLIST) { if (setting == BlacksmithSetting.ENCHANTMENT_BLOCKLIST) {
updateEnchantmentBlocklist(); updateEnchantmentBlocklist();
} }
} }
@ -92,13 +88,13 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The current value of the setting</p> * @return <p>The current value of the setting</p>
*/ */
public Object getRawValue(BlacksmithNPCSetting setting) { public Object getRawValue(BlacksmithSetting setting) {
return currentValues.get(setting); return currentValues.get(setting);
} }
@Override @Override
public String getBusyWithPlayerMessage() { public String getBusyWithPlayerMessage() {
return asString(BlacksmithNPCSetting.BUSY_WITH_PLAYER_MESSAGE); return asString(BlacksmithSetting.BUSY_WITH_PLAYER_MESSAGE);
} }
/** /**
@ -107,7 +103,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The busy reforging message</p> * @return <p>The busy reforging message</p>
*/ */
public String getBusyWorkingMessage() { public String getBusyWorkingMessage() {
return asString(BlacksmithNPCSetting.BUSY_WITH_REFORGE_MESSAGE); return asString(BlacksmithSetting.BUSY_WITH_REFORGE_MESSAGE);
} }
/** /**
@ -116,7 +112,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The message to use for displaying item cost</p> * @return <p>The message to use for displaying item cost</p>
*/ */
public String getCostMessage() { public String getCostMessage() {
return asString(BlacksmithNPCSetting.COST_MESSAGE); return asString(BlacksmithSetting.COST_MESSAGE);
} }
/** /**
@ -125,7 +121,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The invalid item message</p> * @return <p>The invalid item message</p>
*/ */
public String getInvalidItemMessage() { public String getInvalidItemMessage() {
return asString(BlacksmithNPCSetting.INVALID_ITEM_MESSAGE); return asString(BlacksmithSetting.INVALID_ITEM_MESSAGE);
} }
/** /**
@ -134,12 +130,12 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The not damaged message</p> * @return <p>The not damaged message</p>
*/ */
public String getNotDamagedMessage() { public String getNotDamagedMessage() {
return asString(BlacksmithNPCSetting.NOT_DAMAGED_MESSAGE); return asString(BlacksmithSetting.NOT_DAMAGED_MESSAGE);
} }
@Override @Override
public String getStartWorkingMessage() { public String getStartWorkingMessage() {
return asString(BlacksmithNPCSetting.START_REFORGE_MESSAGE); return asString(BlacksmithSetting.START_REFORGE_MESSAGE);
} }
/** /**
@ -148,7 +144,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The reforge success message</p> * @return <p>The reforge success message</p>
*/ */
public String getSuccessMessage() { public String getSuccessMessage() {
return asString(BlacksmithNPCSetting.SUCCESS_MESSAGE); return asString(BlacksmithSetting.SUCCESS_MESSAGE);
} }
/** /**
@ -157,7 +153,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The reforge fail message</p> * @return <p>The reforge fail message</p>
*/ */
public String getFailMessage() { public String getFailMessage() {
return asString(BlacksmithNPCSetting.FAIL_MESSAGE); return asString(BlacksmithSetting.FAIL_MESSAGE);
} }
/** /**
@ -166,12 +162,12 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The insufficient funds message</p> * @return <p>The insufficient funds message</p>
*/ */
public String getInsufficientFundsMessage() { public String getInsufficientFundsMessage() {
return asString(BlacksmithNPCSetting.INSUFFICIENT_FUNDS_MESSAGE); return asString(BlacksmithSetting.INSUFFICIENT_FUNDS_MESSAGE);
} }
@Override @Override
public String getCoolDownUnexpiredMessage() { public String getCoolDownUnexpiredMessage() {
return asString(BlacksmithNPCSetting.COOL_DOWN_UNEXPIRED_MESSAGE); return asString(BlacksmithSetting.COOL_DOWN_UNEXPIRED_MESSAGE);
} }
/** /**
@ -180,7 +176,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The item changed message</p> * @return <p>The item changed message</p>
*/ */
public String getItemChangedMessage() { public String getItemChangedMessage() {
return asString(BlacksmithNPCSetting.ITEM_UNEXPECTEDLY_CHANGED_MESSAGE); return asString(BlacksmithSetting.ITEM_UNEXPECTEDLY_CHANGED_MESSAGE);
} }
/** /**
@ -191,7 +187,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>All items reforge-able by this NPC</p> * @return <p>All items reforge-able by this NPC</p>
*/ */
public List<Material> getReforgeAbleItems() { public List<Material> getReforgeAbleItems() {
Object currentValue = currentValues.get(BlacksmithNPCSetting.REFORGE_ABLE_ITEMS); Object currentValue = currentValues.get(BlacksmithSetting.REFORGE_ABLE_ITEMS);
if (currentValue == null || String.valueOf(currentValue).isEmpty()) { if (currentValue == null || String.valueOf(currentValue).isEmpty()) {
return globalBlacksmithSettings.getReforgeAbleItems(); return globalBlacksmithSettings.getReforgeAbleItems();
} else { } else {
@ -205,7 +201,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The list of blocked enchantments</p> * @return <p>The list of blocked enchantments</p>
*/ */
public List<Enchantment> getEnchantmentBlocklist() { public List<Enchantment> getEnchantmentBlocklist() {
Object currentValue = currentValues.get(BlacksmithNPCSetting.ENCHANTMENT_BLOCKLIST); Object currentValue = currentValues.get(BlacksmithSetting.ENCHANTMENT_BLOCKLIST);
if (currentValue == null || String.valueOf(currentValue).isEmpty()) { if (currentValue == null || String.valueOf(currentValue).isEmpty()) {
return globalBlacksmithSettings.getEnchantmentBlocklist(); return globalBlacksmithSettings.getEnchantmentBlocklist();
} else { } else {
@ -219,7 +215,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The minimum reforge delay</p> * @return <p>The minimum reforge delay</p>
*/ */
public int getMinReforgeDelay() { public int getMinReforgeDelay() {
return asInt(BlacksmithNPCSetting.MIN_REFORGE_DELAY); return asInt(BlacksmithSetting.MIN_REFORGE_DELAY);
} }
/** /**
@ -228,7 +224,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The maximum reforge delay</p> * @return <p>The maximum reforge delay</p>
*/ */
public int getMaxReforgeDelay() { public int getMaxReforgeDelay() {
return asInt(BlacksmithNPCSetting.MAX_REFORGE_DELAY); return asInt(BlacksmithSetting.MAX_REFORGE_DELAY);
} }
/** /**
@ -237,7 +233,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The reforge cool-down</p> * @return <p>The reforge cool-down</p>
*/ */
public int getReforgeCoolDown() { public int getReforgeCoolDown() {
return asInt(BlacksmithNPCSetting.REFORGE_COOL_DOWN); return asInt(BlacksmithSetting.REFORGE_COOL_DOWN);
} }
/** /**
@ -246,7 +242,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The fail chance</p> * @return <p>The fail chance</p>
*/ */
public int getFailChance() { public int getFailChance() {
return asInt(BlacksmithNPCSetting.FAIL_CHANCE); return asInt(BlacksmithSetting.FAIL_CHANCE);
} }
/** /**
@ -255,7 +251,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>Whether enchantments should be removed</p> * @return <p>Whether enchantments should be removed</p>
*/ */
public boolean getFailRemovesEnchantments() { public boolean getFailRemovesEnchantments() {
return asBoolean(BlacksmithNPCSetting.FAIL_REMOVE_ENCHANTMENTS); return asBoolean(BlacksmithSetting.FAIL_REMOVE_ENCHANTMENTS);
} }
/** /**
@ -264,7 +260,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The extra enchantment chance</p> * @return <p>The extra enchantment chance</p>
*/ */
public int getExtraEnchantmentChance() { public int getExtraEnchantmentChance() {
return asInt(BlacksmithNPCSetting.EXTRA_ENCHANTMENT_CHANCE); return asInt(BlacksmithSetting.EXTRA_ENCHANTMENT_CHANCE);
} }
/** /**
@ -273,7 +269,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The maximum enchantments</p> * @return <p>The maximum enchantments</p>
*/ */
public int getMaxEnchantments() { public int getMaxEnchantments() {
return asInt(BlacksmithNPCSetting.MAX_ENCHANTMENTS); return asInt(BlacksmithSetting.MAX_ENCHANTMENTS);
} }
/** /**
@ -282,7 +278,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>Whether to drop reforged items on the ground</p> * @return <p>Whether to drop reforged items on the ground</p>
*/ */
public boolean getDropItem() { public boolean getDropItem() {
return asBoolean(BlacksmithNPCSetting.DROP_ITEM); return asBoolean(BlacksmithSetting.DROP_ITEM);
} }
/** /**
@ -291,12 +287,12 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>The title of the blacksmith</p> * @return <p>The title of the blacksmith</p>
*/ */
public String getBlacksmithTitle() { public String getBlacksmithTitle() {
return asString(BlacksmithNPCSetting.BLACKSMITH_TITLE); return asString(BlacksmithSetting.BLACKSMITH_TITLE);
} }
@Override @Override
public boolean getDisableCoolDown() { public boolean getDisableCoolDown() {
return asInt(BlacksmithNPCSetting.REFORGE_COOL_DOWN) <= 0; return asInt(BlacksmithSetting.REFORGE_COOL_DOWN) <= 0;
} }
/** /**
@ -305,7 +301,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @return <p>True if this blacksmith is able to repair anvils</p> * @return <p>True if this blacksmith is able to repair anvils</p>
*/ */
public boolean getRepairAnvils() { public boolean getRepairAnvils() {
return asBoolean(BlacksmithNPCSetting.REPAIR_ANVILS); return asBoolean(BlacksmithSetting.REPAIR_ANVILS);
} }
/** /**
@ -316,7 +312,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as an integer</p> * @return <p>The value of the given setting as an integer</p>
*/ */
private int asInt(BlacksmithNPCSetting setting) { private int asInt(BlacksmithSetting setting) {
return ConfigHelper.asInt(getValue(setting)); return ConfigHelper.asInt(getValue(setting));
} }
@ -326,7 +322,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as a string</p> * @return <p>The value of the given setting as a string</p>
*/ */
private String asString(BlacksmithNPCSetting setting) { private String asString(BlacksmithSetting setting) {
return getValue(setting).toString(); return getValue(setting).toString();
} }
@ -336,7 +332,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as a boolean</p> * @return <p>The value of the given setting as a boolean</p>
*/ */
private boolean asBoolean(BlacksmithNPCSetting setting) { private boolean asBoolean(BlacksmithSetting setting) {
return ConfigHelper.asBoolean(getValue(setting)); return ConfigHelper.asBoolean(getValue(setting));
} }
@ -346,11 +342,11 @@ public class BlacksmithNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The current value</p> * @return <p>The current value</p>
*/ */
private Object getValue(BlacksmithNPCSetting setting) { private Object getValue(BlacksmithSetting setting) {
Object value = currentValues.get(setting); Object value = currentValues.get(setting);
//If not set, use the default value from the config.yml file //If not set, use the default value from the config.yml file
if (value == null) { if (value == null) {
Map<BlacksmithNPCSetting, Object> defaultNPCSettings = globalBlacksmithSettings.getDefaultNPCSettings(); Map<BlacksmithSetting, Object> defaultNPCSettings = globalBlacksmithSettings.getDefaultNPCSettings();
if (defaultNPCSettings.containsKey(setting)) { if (defaultNPCSettings.containsKey(setting)) {
value = defaultNPCSettings.get(setting); value = defaultNPCSettings.get(setting);
} }
@ -389,7 +385,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
*/ */
private void updateEnchantmentBlocklist() { private void updateEnchantmentBlocklist() {
this.enchantmentBlocklist.clear(); this.enchantmentBlocklist.clear();
List<String> enchantments = ConfigHelper.asStringList(getValue(BlacksmithNPCSetting.ENCHANTMENT_BLOCKLIST)); List<String> enchantments = ConfigHelper.asStringList(getValue(BlacksmithSetting.ENCHANTMENT_BLOCKLIST));
if (enchantments != null) { if (enchantments != null) {
this.enchantmentBlocklist.addAll(getEnchantmentBlocklist(enchantments)); this.enchantmentBlocklist.addAll(getEnchantmentBlocklist(enchantments));
} }
@ -425,7 +421,7 @@ public class BlacksmithNPCSettings implements TraitSettings {
*/ */
private void updateReforgeAbleItems() { private void updateReforgeAbleItems() {
this.reforgeAbleItems.clear(); this.reforgeAbleItems.clear();
List<String> materialStrings = ConfigHelper.asStringList(getValue(BlacksmithNPCSetting.REFORGE_ABLE_ITEMS)); List<String> materialStrings = ConfigHelper.asStringList(getValue(BlacksmithSetting.REFORGE_ABLE_ITEMS));
if (materialStrings != null) { if (materialStrings != null) {
this.reforgeAbleItems.addAll(getReforgeAbleItems(materialStrings)); this.reforgeAbleItems.addAll(getReforgeAbleItems(materialStrings));
} }

View File

@ -1,62 +1,69 @@
package net.knarcraft.blacksmith.config.blacksmith; package net.knarcraft.blacksmith.config.blacksmith;
import net.knarcraft.blacksmith.config.NPCSetting; import net.knarcraft.blacksmith.config.Setting;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/** /**
* An enum representing all of Blacksmith's settings * An enum representing all of Blacksmith's settings
*/ */
public enum BlacksmithNPCSetting implements NPCSetting { public enum BlacksmithSetting implements Setting {
/** /**
* The setting for whether the NPC should drop an item to the ground when finished * The setting for whether the NPC should drop an item to the ground when finished
* *
* <p>If set to false, the item will be directly put in the player's inventory instead</p> * <p>If set to false, the item will be directly put in the player's inventory instead</p>
*/ */
DROP_ITEM("dropItem", SettingValueType.BOOLEAN, true, "dropItem"), DROP_ITEM("dropItem", SettingValueType.BOOLEAN, true, "dropItem", true, false),
/** /**
* The setting for the chance of a reforging to fail * The setting for the chance of a reforging to fail
*/ */
FAIL_CHANCE("failReforgeChance", SettingValueType.PERCENTAGE, 10, "failReforgeChance"), FAIL_CHANCE("failReforgeChance", SettingValueType.PERCENTAGE, 10, "failReforgeChance",
true, false),
/** /**
* The setting for whether failing a reforging should downgrade/remove enchantments as well * The setting for whether failing a reforging should downgrade/remove enchantments as well
*/ */
FAIL_REMOVE_ENCHANTMENTS("failReforgeRemovesEnchantments", SettingValueType.BOOLEAN, false, FAIL_REMOVE_ENCHANTMENTS("failReforgeRemovesEnchantments", SettingValueType.BOOLEAN, false,
"failReforgeRemovesEnchantments"), "failReforgeRemovesEnchantments", true, false),
/** /**
* The setting for the chance of an additional enchantment being added * The setting for the chance of an additional enchantment being added
*/ */
EXTRA_ENCHANTMENT_CHANCE("extraEnchantmentChance", SettingValueType.PERCENTAGE, 5, EXTRA_ENCHANTMENT_CHANCE("extraEnchantmentChance", SettingValueType.PERCENTAGE, 5,
"extraEnchantmentChance"), "extraEnchantmentChance", true, false),
/** /**
* The setting for the maximum amount of enchantments that can be added to an item * The setting for the maximum amount of enchantments that can be added to an item
*/ */
MAX_ENCHANTMENTS("maxEnchantments", SettingValueType.POSITIVE_INTEGER, 3, "maxEnchantments"), MAX_ENCHANTMENTS("maxEnchantments", SettingValueType.POSITIVE_INTEGER, 3,
"maxEnchantments", true, false),
/** /**
* The maximum amount of seconds a player may need to wait for the reforging to finish * The maximum amount of seconds a player may need to wait for the reforging to finish
*/ */
MAX_REFORGE_DELAY("delaysInSeconds.maximum", SettingValueType.POSITIVE_INTEGER, 30, "maxReforgeDelay"), MAX_REFORGE_DELAY("delaysInSeconds.maximum", SettingValueType.POSITIVE_INTEGER, 30,
"maxReforgeDelay", true, false),
/** /**
* The minimum amount of seconds a player may need to wait for the reforging to finish * The minimum amount of seconds a player may need to wait for the reforging to finish
*/ */
MIN_REFORGE_DELAY("delaysInSeconds.minimum", SettingValueType.POSITIVE_INTEGER, 5, "minReforgeDelay"), MIN_REFORGE_DELAY("delaysInSeconds.minimum", SettingValueType.POSITIVE_INTEGER, 5,
"minReforgeDelay", true, false),
/** /**
* The setting for number of seconds a player has to wait between each usage of the blacksmith * The setting for number of seconds a player has to wait between each usage of the blacksmith
*/ */
REFORGE_COOL_DOWN("delaysInSeconds.reforgeCoolDown", SettingValueType.POSITIVE_INTEGER, 60, "reforgeCoolDown"), REFORGE_COOL_DOWN("delaysInSeconds.reforgeCoolDown", SettingValueType.POSITIVE_INTEGER, 60,
"reforgeCoolDown", true, false),
/** /**
* The setting for which items the blacksmith is able to reforge * The setting for which items the blacksmith is able to reforge
*/ */
REFORGE_ABLE_ITEMS("reforgeAbleItems", SettingValueType.REFORGE_ABLE_ITEMS, "", "reforgeAbleItems"), REFORGE_ABLE_ITEMS("reforgeAbleItems", SettingValueType.REFORGE_ABLE_ITEMS, "",
"reforgeAbleItems", true, false),
/** /**
* The setting for the title used to display which kind of blacksmith the NPC is * The setting for the title used to display which kind of blacksmith the NPC is
@ -64,18 +71,20 @@ public enum BlacksmithNPCSetting implements NPCSetting {
* <p>While this should be entirely configurable, values such as armor-smith, sword-smith and similar, which * <p>While this should be entirely configurable, values such as armor-smith, sword-smith and similar, which
* describe the blacksmith's specialization, and thus the range of reforge-able items, is expected.</p> * describe the blacksmith's specialization, and thus the range of reforge-able items, is expected.</p>
*/ */
BLACKSMITH_TITLE("blacksmithTitle", SettingValueType.STRING, "blacksmith", "blacksmithTitle"), BLACKSMITH_TITLE("blacksmithTitle", SettingValueType.STRING, "blacksmith",
"blacksmithTitle", true, false),
/** /**
* The setting for the enchantments a blacksmith cannot apply to items * The setting for the enchantments a blacksmith cannot apply to items
*/ */
ENCHANTMENT_BLOCKLIST("enchantmentBlocklist", SettingValueType.STRING_LIST, new String[]{"binding_curse", ENCHANTMENT_BLOCKLIST("enchantmentBlocklist", SettingValueType.STRING_LIST, new String[]{"binding_curse",
"mending", "vanishing_curse"}, "enchantmentBlocklist"), "mending", "vanishing_curse"}, "enchantmentBlocklist", true, false),
/** /**
* Whether to allow this blacksmith to repair anvils * Whether to allow this blacksmith to repair anvils
*/ */
REPAIR_ANVILS("reforgeAnvils", SettingValueType.BOOLEAN, false, "reforgeAnvils"), REPAIR_ANVILS("reforgeAnvils", SettingValueType.BOOLEAN, false, "reforgeAnvils",
true, false),
/*----------- /*-----------
| Messages | | Messages |
@ -85,74 +94,137 @@ public enum BlacksmithNPCSetting implements NPCSetting {
* The message displayed when the blacksmith is busy with another player * The message displayed when the blacksmith is busy with another player
*/ */
BUSY_WITH_PLAYER_MESSAGE("messages.busyPlayerMessage", SettingValueType.STRING, BUSY_WITH_PLAYER_MESSAGE("messages.busyPlayerMessage", SettingValueType.STRING,
"&cI'm busy at the moment. Come back later!", "busyPlayerMessage"), "&cI'm busy at the moment. Come back later!", "busyPlayerMessage",
true, true),
/** /**
* The message displayed when the blacksmith is already reforging something for the player * The message displayed when the blacksmith is already reforging something for the player
*/ */
BUSY_WITH_REFORGE_MESSAGE("messages.busyReforgeMessage", SettingValueType.STRING, BUSY_WITH_REFORGE_MESSAGE("messages.busyReforgeMessage", SettingValueType.STRING,
"&cI'm working on it. Be patient! I'll finish {time}!", "busyReforgeMessage"), "&cI'm working on it. Be patient! I'll finish {time}!", "busyReforgeMessage",
true, true),
/** /**
* The message displayed if the player has to wait for the cool-down to expire * The message displayed if the player has to wait for the cool-down to expire
*/ */
COOL_DOWN_UNEXPIRED_MESSAGE("messages.coolDownUnexpiredMessage", SettingValueType.STRING, COOL_DOWN_UNEXPIRED_MESSAGE("messages.coolDownUnexpiredMessage", SettingValueType.STRING,
"&cYou've already had your chance! Give me a break! I'll be ready {time}!", "&cYou've already had your chance! Give me a break! I'll be ready {time}!",
"coolDownUnexpiredMessage"), "coolDownUnexpiredMessage", true, true),
/** /**
* The message displayed when displaying the cost of reforging the held item to the player * The message displayed when displaying the cost of reforging the held item to the player
*/ */
COST_MESSAGE("messages.costMessage", SettingValueType.STRING, COST_MESSAGE("messages.costMessage", SettingValueType.STRING,
"&eIt will cost &a{cost}&e to reforge that &a{item}&e! Click again to reforge!", "costMessage"), "&eIt will cost &a{cost}&e to reforge that &a{item}&e! Click again to reforge!",
"costMessage", true, true),
/** /**
* The message displayed if the blacksmith fails reforging an item * The message displayed if the blacksmith fails reforging an item
*/ */
FAIL_MESSAGE("messages.failReforgeMessage", SettingValueType.STRING, FAIL_MESSAGE("messages.failReforgeMessage", SettingValueType.STRING,
"&cWhoops! Didn't mean to do that! Maybe next time?", "failReforgeMessage"), "&cWhoops! Didn't mean to do that! Maybe next time?", "failReforgeMessage",
true, true),
/** /**
* The message displayed if a player is unable to pay the blacksmith * The message displayed if a player is unable to pay the blacksmith
*/ */
INSUFFICIENT_FUNDS_MESSAGE("messages.insufficientFundsMessage", SettingValueType.STRING, INSUFFICIENT_FUNDS_MESSAGE("messages.insufficientFundsMessage", SettingValueType.STRING,
"&cYou don't have enough money to reforge that item!", "insufficientFundsMessage"), "&cYou don't have enough money to reforge that item!", "insufficientFundsMessage",
true, true),
/** /**
* The message displayed if the blacksmith encounters an item they cannot reforge * The message displayed if the blacksmith encounters an item they cannot reforge
*/ */
INVALID_ITEM_MESSAGE("messages.invalidItemMessage", SettingValueType.STRING, INVALID_ITEM_MESSAGE("messages.invalidItemMessage", SettingValueType.STRING,
"&cI'm sorry, but I'm a/an {title}, I don't know how to reforge that!", "invalidItemMessage"), "&cI'm sorry, but I'm a/an {title}, I don't know how to reforge that!",
"invalidItemMessage", true, true),
/** /**
* The message displayed if a player presents a different item after seeing the price to reforge an item * The message displayed if a player presents a different item after seeing the price to reforge an item
*/ */
ITEM_UNEXPECTEDLY_CHANGED_MESSAGE("messages.itemChangedMessage", SettingValueType.STRING, ITEM_UNEXPECTEDLY_CHANGED_MESSAGE("messages.itemChangedMessage", SettingValueType.STRING,
"&cThat's not the item you wanted to reforge before!", "itemChangedMessage"), "&cThat's not the item you wanted to reforge before!", "itemChangedMessage",
true, true),
/** /**
* The message displayed when the blacksmith starts reforging an item * The message displayed when the blacksmith starts reforging an item
*/ */
START_REFORGE_MESSAGE("messages.startReforgeMessage", SettingValueType.STRING, START_REFORGE_MESSAGE("messages.startReforgeMessage", SettingValueType.STRING,
"&eOk, let's see what I can do...", "startReforgeMessage"), "&eOk, let's see what I can do...", "startReforgeMessage", true, true),
/** /**
* The message displayed when the blacksmith successfully finishes reforging an item * The message displayed when the blacksmith successfully finishes reforging an item
*/ */
SUCCESS_MESSAGE("messages.successMessage", SettingValueType.STRING, SUCCESS_MESSAGE("messages.successMessage", SettingValueType.STRING,
"There you go! All better!", "successMessage"), "There you go! All better!", "successMessage", true, true),
/** /**
* The message displayed when trying to reforge an item with full durability * The message displayed when trying to reforge an item with full durability
*/ */
NOT_DAMAGED_MESSAGE("messages.notDamagedMessage", SettingValueType.STRING, NOT_DAMAGED_MESSAGE("messages.notDamagedMessage", SettingValueType.STRING,
"&cThat item is not in need of repair", "notDamagedMessage"); "&cThat item is not in need of repair", "notDamagedMessage", true, true),
/*------------------
| Global settings |
------------------*/
/**
* The base price for repairing, regardless of durability
*
* <p>This allows specifying a price for each item, by setting basePrice.item_name.</p>
*/
BASE_PRICE("basePrice.default", SettingValueType.POSITIVE_DOUBLE, 10.0, "basePrice",
false, false),
/**
* The base price for each durability point
*
* <p>If natural cost, this is the cost each missing durability point will add to the cost. If not natural cost,
* this is the cost each present durability point will add to the cost. This allows specifying a price per
* durability point value for each item, by setting pricePerDurabilityPoint.item_name</p>
*/
PRICE_PER_DURABILITY_POINT("pricePerDurabilityPoint.default", SettingValueType.POSITIVE_DOUBLE,
0.005, "pricePerDurabilityPoint", false, false),
/**
* The price increase for each level of each present enchantment
*
* <p>This can be specified for each possible enchantment by setting enchantment-cost.enchantment_name</p>
*/
ENCHANTMENT_COST("enchantmentCost.default", SettingValueType.POSITIVE_DOUBLE, 5.0,
"enchantmentCost", false, false),
/**
* Whether the cost should increase for damage taken, as opposed to increase for durability present
*/
NATURAL_COST("useNaturalCost", SettingValueType.BOOLEAN, true, "useNaturalCost",
false, false),
/**
* Whether to show exact time when displaying the wait time for a reforging or the cool-down
*/
SHOW_EXACT_TIME("showExactTime", SettingValueType.BOOLEAN, false, "showExactTime",
false, false),
/**
* The cost for repairing a chipped anvil
*/
ANVIL_CHIPPED_COST("chippedAnvilReforgingCost", SettingValueType.POSITIVE_DOUBLE, 10.0,
"chippedAnvilReforgingCost", false, false),
/**
* The cost for repairing a damaged anvil
*/
ANVIL_DAMAGED_COST("damagedAnvilReforgingCost", SettingValueType.POSITIVE_DOUBLE, 20.0,
"damagedAnvilReforgingCost", false, false);
private final String path; private final String path;
private final String childPath; private final String childPath;
private final Object value; private final Object value;
private final String commandName; private final String commandName;
private final SettingValueType valueType; private final SettingValueType valueType;
private final boolean isPerNPC;
private final boolean isMessage;
/** /**
* Instantiates a new setting * Instantiates a new setting
@ -161,13 +233,22 @@ public enum BlacksmithNPCSetting implements NPCSetting {
* @param valueType <p>The type of value used by this setting</p> * @param valueType <p>The type of value used by this setting</p>
* @param value <p>The default value of this setting</p> * @param value <p>The default value of this setting</p>
* @param commandName <p>The name of the command used to change this setting</p> * @param commandName <p>The name of the command used to change this setting</p>
* @param isPerNPC <p>Whether this setting is per-NPC or global</p>
* @param isMessage <p>Whether this option is for an NPC message</p>
*/ */
BlacksmithNPCSetting(String path, SettingValueType valueType, Object value, String commandName) { BlacksmithSetting(String path, SettingValueType valueType, Object value, String commandName, boolean isPerNPC,
boolean isMessage) {
if (isPerNPC) {
this.path = "blacksmith.defaults." + path; this.path = "blacksmith.defaults." + path;
} else {
this.path = "blacksmith.global." + path;
}
this.value = value; this.value = value;
this.valueType = valueType; this.valueType = valueType;
this.childPath = path; this.childPath = path;
this.commandName = commandName; this.commandName = commandName;
this.isPerNPC = isPerNPC;
this.isMessage = isMessage;
} }
@Override @Override
@ -195,4 +276,29 @@ public enum BlacksmithNPCSetting implements NPCSetting {
return this.valueType; return this.valueType;
} }
@Override
public boolean isPerNPC() {
return this.isPerNPC;
}
@Override
public boolean isMessage() {
return this.isMessage;
}
/**
* Gets the blacksmith setting specified by the input string
*
* @param input <p>The input to check</p>
* @return <p>The matching blacksmith setting, or null if not found</p>
*/
public static @Nullable BlacksmithSetting getSetting(@NotNull String input) {
for (BlacksmithSetting blacksmithSetting : BlacksmithSetting.values()) {
if (input.equalsIgnoreCase(blacksmithSetting.commandName)) {
return blacksmithSetting;
}
}
return null;
}
} }

View File

@ -1,109 +0,0 @@
package net.knarcraft.blacksmith.config.blacksmith;
import net.knarcraft.blacksmith.config.GlobalSetting;
import net.knarcraft.blacksmith.config.SettingValueType;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
/**
* Settings which are the same for every blacksmith
*/
public enum GlobalBlacksmithSetting implements GlobalSetting {
/**
* The base price for repairing, regardless of durability
*
* <p>This allows specifying a price for each item, by setting basePrice.item_name.</p>
*/
BASE_PRICE("basePrice.default", SettingValueType.POSITIVE_DOUBLE, 10.0, "basePrice"),
/**
* The base price for each durability point
*
* <p>If natural cost, this is the cost each missing durability point will add to the cost. If not natural cost,
* this is the cost each present durability point will add to the cost. This allows specifying a price per
* durability point value for each item, by setting pricePerDurabilityPoint.item_name</p>
*/
PRICE_PER_DURABILITY_POINT("pricePerDurabilityPoint.default", SettingValueType.POSITIVE_DOUBLE,
0.005, "pricePerDurabilityPoint"),
/**
* The price increase for each level of each present enchantment
*
* <p>This can be specified for each possible enchantment by setting enchantment-cost.enchantment_name</p>
*/
ENCHANTMENT_COST("enchantmentCost.default", SettingValueType.POSITIVE_DOUBLE, 5.0,
"enchantmentCost"),
/**
* Whether the cost should increase for damage taken, as opposed to increase for durability present
*/
NATURAL_COST("useNaturalCost", SettingValueType.BOOLEAN, true, "useNaturalCost"),
/**
* Whether to show exact time when displaying the wait time for a reforging or the cool-down
*/
SHOW_EXACT_TIME("showExactTime", SettingValueType.BOOLEAN, false, "showExactTime"),
/**
* The cost for repairing a chipped anvil
*/
ANVIL_CHIPPED_COST("chippedAnvilReforgingCost", SettingValueType.POSITIVE_DOUBLE, 10.0,
"chippedAnvilReforgingCost"),
/**
* The cost for repairing a damaged anvil
*/
ANVIL_DAMAGED_COST("damagedAnvilReforgingCost", SettingValueType.POSITIVE_DOUBLE, 20.0,
"damagedAnvilReforgingCost");
private final String path;
private final String parent;
private final String commandName;
private final Object value;
private final SettingValueType valueType;
/**
* Instantiates a new setting
*
* @param path <p>The full config path for this setting</p>
* @param valueType <p>The type of value used by this setting</p>
* @param value <p>The default value of this setting</p>
* @param commandName <p>The name of the command used to change this setting</p>
*/
GlobalBlacksmithSetting(String path, SettingValueType valueType, Object value, String commandName) {
this.path = "blacksmith.global." + path;
this.value = value;
this.commandName = commandName;
this.valueType = valueType;
String[] pathParts = path.split("\\.");
this.parent = String.join(".", Arrays.copyOfRange(pathParts, 0, pathParts.length - 1));
}
@Override
public @NotNull String getPath() {
return path;
}
@Override
public @NotNull String getParent() {
return parent;
}
@Override
public @NotNull Object getDefaultValue() {
return value;
}
@Override
public @NotNull String getCommandName() {
return commandName;
}
@Override
public @NotNull SettingValueType getValueType() {
return this.valueType;
}
}

View File

@ -4,6 +4,7 @@ import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.YamlStorage; import net.citizensnpcs.api.util.YamlStorage;
import net.knarcraft.blacksmith.BlacksmithPlugin; import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.config.Settings;
import net.knarcraft.blacksmith.util.ConfigHelper; import net.knarcraft.blacksmith.util.ConfigHelper;
import net.knarcraft.blacksmith.util.InputParsingHelper; import net.knarcraft.blacksmith.util.InputParsingHelper;
import net.knarcraft.blacksmith.util.ItemHelper; import net.knarcraft.blacksmith.util.ItemHelper;
@ -20,15 +21,14 @@ import java.util.logging.Level;
/** /**
* A class which keeps track of all default NPC settings and all global settings * A class which keeps track of all default NPC settings and all global settings
*/ */
public class GlobalBlacksmithSettings { public class GlobalBlacksmithSettings implements Settings<BlacksmithSetting> {
private final Map<Material, Double> materialBasePrices = new HashMap<>(); private final Map<Material, Double> materialBasePrices = new HashMap<>();
private final Map<Material, Double> materialPricePerDurabilityPoints = new HashMap<>(); private final Map<Material, Double> materialPricePerDurabilityPoints = new HashMap<>();
private final Map<Enchantment, Double> enchantmentCosts = new HashMap<>(); private final Map<Enchantment, Double> enchantmentCosts = new HashMap<>();
private final Map<BlacksmithNPCSetting, Object> defaultNPCSettings = new HashMap<>(); private final Map<BlacksmithSetting, Object> settings = new HashMap<>();
private final List<Material> defaultReforgeAbleMaterials = new ArrayList<>(); private final List<Material> defaultReforgeAbleMaterials = new ArrayList<>();
private final List<Enchantment> defaultEnchantmentBlocklist = new ArrayList<>(); private final List<Enchantment> defaultEnchantmentBlocklist = new ArrayList<>();
private final Map<GlobalBlacksmithSetting, Object> globalSettings = new HashMap<>();
private final YamlStorage defaultConfig; private final YamlStorage defaultConfig;
@ -47,78 +47,53 @@ public class GlobalBlacksmithSettings {
* Loads all configuration values from the config file * Loads all configuration values from the config file
*/ */
public void load() { public void load() {
//Load the config from disk // Load the config from disk
defaultConfig.load(); defaultConfig.load();
DataKey root = defaultConfig.getKey(""); DataKey root = defaultConfig.getKey("");
//Just in case, clear existing values // Just in case, clear existing values
defaultNPCSettings.clear(); settings.clear();
globalSettings.clear();
materialBasePrices.clear(); materialBasePrices.clear();
materialPricePerDurabilityPoints.clear(); materialPricePerDurabilityPoints.clear();
enchantmentCosts.clear(); enchantmentCosts.clear();
//Load/Save NPC default settings // Load/Save settings
loadDefaultNPCSettings(root);
//Load/Save global settings
loadGlobalSettings(root); loadGlobalSettings(root);
//Save any modified values to disk // Save any modified values to disk
defaultConfig.save(); defaultConfig.save();
} }
/** /**
* Changes the value of the given setting * Changes the value of the given setting
* *
* @param globalBlacksmithSetting <p>The global setting to change</p> * @param blacksmithSetting <p>The default NPC setting to change</p>
* @param newValue <p>The new value of the setting</p>
*/
public void changeValue(GlobalBlacksmithSetting globalBlacksmithSetting, Object newValue) {
globalSettings.put(globalBlacksmithSetting, newValue);
save();
}
/**
* Changes the value of the given setting
*
* @param blacksmithNpcSetting <p>The default NPC setting to change</p>
* @param newValue <p>The new value for the setting</p> * @param newValue <p>The new value for the setting</p>
*/ */
public void changeValue(BlacksmithNPCSetting blacksmithNpcSetting, Object newValue) { public void changeValue(BlacksmithSetting blacksmithSetting, Object newValue) {
if (blacksmithNpcSetting.getValueType() == SettingValueType.STRING_LIST || if (blacksmithSetting.getValueType() == SettingValueType.STRING_LIST ||
blacksmithNpcSetting.getValueType() == SettingValueType.REFORGE_ABLE_ITEMS) { blacksmithSetting.getValueType() == SettingValueType.REFORGE_ABLE_ITEMS) {
//Workaround to make sure it's treated as the correct type //Workaround to make sure it's treated as the correct type
defaultNPCSettings.put(blacksmithNpcSetting, newValue == null ? null : ConfigHelper.asStringList(newValue)); settings.put(blacksmithSetting, newValue == null ? null : ConfigHelper.asStringList(newValue));
} else { } else {
defaultNPCSettings.put(blacksmithNpcSetting, newValue); settings.put(blacksmithSetting, newValue);
} }
save(); save();
if (blacksmithNpcSetting == BlacksmithNPCSetting.REFORGE_ABLE_ITEMS) { if (blacksmithSetting == BlacksmithSetting.REFORGE_ABLE_ITEMS) {
loadReforgeAbleItems(); loadReforgeAbleItems();
} else if (blacksmithNpcSetting == BlacksmithNPCSetting.ENCHANTMENT_BLOCKLIST) { } else if (blacksmithSetting == BlacksmithSetting.ENCHANTMENT_BLOCKLIST) {
loadEnchantmentBlocklist(); loadEnchantmentBlocklist();
} }
} }
/**
* Gets the current raw value of the given global setting
*
* @param globalBlacksmithSetting <p>The setting to get</p>
* @return <p>The current raw setting value</p>
*/
public Object getRawValue(GlobalBlacksmithSetting globalBlacksmithSetting) {
return globalSettings.get(globalBlacksmithSetting);
}
/** /**
* Gets the current raw value of the given default NPC setting * Gets the current raw value of the given default NPC setting
* *
* @param blacksmithNpcSetting <p>The setting to get</p> * @param blacksmithSetting <p>The setting to get</p>
* @return <p>The current raw setting value</p> * @return <p>The current raw setting value</p>
*/ */
public Object getRawValue(BlacksmithNPCSetting blacksmithNpcSetting) { public Object getRawValue(BlacksmithSetting blacksmithSetting) {
return defaultNPCSettings.get(blacksmithNpcSetting); return settings.get(blacksmithSetting);
} }
/** /**
@ -132,7 +107,7 @@ public class GlobalBlacksmithSettings {
if (newEnchantmentCost < 0) { if (newEnchantmentCost < 0) {
throw new IllegalArgumentException("Enchantment cost cannot be negative!"); throw new IllegalArgumentException("Enchantment cost cannot be negative!");
} }
globalSettings.put(GlobalBlacksmithSetting.ENCHANTMENT_COST, newEnchantmentCost); settings.put(BlacksmithSetting.ENCHANTMENT_COST, newEnchantmentCost);
} else { } else {
if (newEnchantmentCost < 0) { if (newEnchantmentCost < 0) {
enchantmentCosts.put(enchantment, null); enchantmentCosts.put(enchantment, null);
@ -154,7 +129,7 @@ public class GlobalBlacksmithSettings {
if (newPrice < 0) { if (newPrice < 0) {
throw new IllegalArgumentException("Price per durability point cannot be negative!"); throw new IllegalArgumentException("Price per durability point cannot be negative!");
} }
globalSettings.put(GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT, newPrice); settings.put(BlacksmithSetting.PRICE_PER_DURABILITY_POINT, newPrice);
} else { } else {
//Use a negative price to unset the per-item value //Use a negative price to unset the per-item value
if (newPrice < 0) { if (newPrice < 0) {
@ -177,7 +152,7 @@ public class GlobalBlacksmithSettings {
if (newBasePrice < 0) { if (newBasePrice < 0) {
throw new IllegalArgumentException("Base price cannot be negative!"); throw new IllegalArgumentException("Base price cannot be negative!");
} }
globalSettings.put(GlobalBlacksmithSetting.BASE_PRICE, newBasePrice); settings.put(BlacksmithSetting.BASE_PRICE, newBasePrice);
} else { } else {
//Use a negative price to unset the per-item value //Use a negative price to unset the per-item value
if (newBasePrice < 0) { if (newBasePrice < 0) {
@ -194,8 +169,8 @@ public class GlobalBlacksmithSettings {
* *
* @return <p>The current value of the default NPC settings</p> * @return <p>The current value of the default NPC settings</p>
*/ */
public Map<BlacksmithNPCSetting, Object> getDefaultNPCSettings() { public Map<BlacksmithSetting, Object> getDefaultNPCSettings() {
return new HashMap<>(this.defaultNPCSettings); return new HashMap<>(this.settings);
} }
/** /**
@ -207,7 +182,7 @@ public class GlobalBlacksmithSettings {
* @return <p>Whether to use natural cost</p> * @return <p>Whether to use natural cost</p>
*/ */
public boolean getUseNaturalCost() { public boolean getUseNaturalCost() {
return asBoolean(GlobalBlacksmithSetting.NATURAL_COST); return asBoolean(BlacksmithSetting.NATURAL_COST);
} }
/** /**
@ -216,7 +191,7 @@ public class GlobalBlacksmithSettings {
* @return <p>Whether to show exact time</p> * @return <p>Whether to show exact time</p>
*/ */
public boolean getShowExactTime() { public boolean getShowExactTime() {
return asBoolean(GlobalBlacksmithSetting.SHOW_EXACT_TIME); return asBoolean(BlacksmithSetting.SHOW_EXACT_TIME);
} }
/** /**
@ -229,7 +204,7 @@ public class GlobalBlacksmithSettings {
if (materialBasePrices.containsKey(material) && materialBasePrices.get(material) != null) { if (materialBasePrices.containsKey(material) && materialBasePrices.get(material) != null) {
return materialBasePrices.get(material); return materialBasePrices.get(material);
} else { } else {
return asDouble(GlobalBlacksmithSetting.BASE_PRICE); return asDouble(BlacksmithSetting.BASE_PRICE);
} }
} }
@ -244,7 +219,7 @@ public class GlobalBlacksmithSettings {
materialPricePerDurabilityPoints.get(material) != null) { materialPricePerDurabilityPoints.get(material) != null) {
return materialPricePerDurabilityPoints.get(material); return materialPricePerDurabilityPoints.get(material);
} else { } else {
return asDouble(GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT); return asDouble(BlacksmithSetting.PRICE_PER_DURABILITY_POINT);
} }
} }
@ -258,7 +233,7 @@ public class GlobalBlacksmithSettings {
if (enchantmentCosts.containsKey(enchantment) && enchantmentCosts.get(enchantment) != null) { if (enchantmentCosts.containsKey(enchantment) && enchantmentCosts.get(enchantment) != null) {
return enchantmentCosts.get(enchantment); return enchantmentCosts.get(enchantment);
} else { } else {
return asDouble(GlobalBlacksmithSetting.ENCHANTMENT_COST); return asDouble(BlacksmithSetting.ENCHANTMENT_COST);
} }
} }
@ -288,9 +263,9 @@ public class GlobalBlacksmithSettings {
*/ */
public double getAnvilCost(Material material) { public double getAnvilCost(Material material) {
if (material == Material.CHIPPED_ANVIL) { if (material == Material.CHIPPED_ANVIL) {
return asDouble(GlobalBlacksmithSetting.ANVIL_CHIPPED_COST); return asDouble(BlacksmithSetting.ANVIL_CHIPPED_COST);
} else if (material == Material.DAMAGED_ANVIL) { } else if (material == Material.DAMAGED_ANVIL) {
return asDouble(GlobalBlacksmithSetting.ANVIL_DAMAGED_COST); return asDouble(BlacksmithSetting.ANVIL_DAMAGED_COST);
} else { } else {
throw new IllegalArgumentException("An unexpected item was encountered!"); throw new IllegalArgumentException("An unexpected item was encountered!");
} }
@ -304,7 +279,7 @@ public class GlobalBlacksmithSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as a boolean</p> * @return <p>The value of the given setting as a boolean</p>
*/ */
public boolean asBoolean(GlobalBlacksmithSetting setting) { public boolean asBoolean(BlacksmithSetting setting) {
return ConfigHelper.asBoolean(getValue(setting)); return ConfigHelper.asBoolean(getValue(setting));
} }
@ -316,7 +291,7 @@ public class GlobalBlacksmithSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as a double</p> * @return <p>The value of the given setting as a double</p>
*/ */
public double asDouble(GlobalBlacksmithSetting setting) { public double asDouble(BlacksmithSetting setting) {
return ConfigHelper.asDouble(getValue(setting)); return ConfigHelper.asDouble(getValue(setting));
} }
@ -326,8 +301,8 @@ public class GlobalBlacksmithSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The current value</p> * @return <p>The current value</p>
*/ */
private Object getValue(GlobalBlacksmithSetting setting) { private Object getValue(BlacksmithSetting setting) {
Object value = globalSettings.get(setting); Object value = settings.get(setting);
//If not set in config.yml, use the default value from the enum //If not set in config.yml, use the default value from the enum
if (value == null) { if (value == null) {
value = setting.getDefaultValue(); value = setting.getDefaultValue();
@ -341,15 +316,17 @@ public class GlobalBlacksmithSettings {
* @param root <p>The root node of all global settings</p> * @param root <p>The root node of all global settings</p>
*/ */
private void loadGlobalSettings(DataKey root) { private void loadGlobalSettings(DataKey root) {
for (GlobalBlacksmithSetting globalBlacksmithSetting : GlobalBlacksmithSetting.values()) { for (BlacksmithSetting blacksmithSetting : BlacksmithSetting.values()) {
if (!root.keyExists(globalBlacksmithSetting.getPath())) { if (!root.keyExists(blacksmithSetting.getPath())) {
//If the setting does not exist in the config file, add it //If the setting does not exist in the config file, add it
root.setRaw(globalBlacksmithSetting.getPath(), globalBlacksmithSetting.getDefaultValue()); root.setRaw(blacksmithSetting.getPath(), blacksmithSetting.getDefaultValue());
} else { } else {
//Set the setting to the value found in the path //Set the setting to the value found in the path
globalSettings.put(globalBlacksmithSetting, root.getRaw(globalBlacksmithSetting.getPath())); settings.put(blacksmithSetting, root.getRaw(blacksmithSetting.getPath()));
} }
} }
loadReforgeAbleItems();
loadEnchantmentBlocklist();
//Load all base prices //Load all base prices
loadBasePrices(root); loadBasePrices(root);
@ -358,7 +335,7 @@ public class GlobalBlacksmithSettings {
loadPricesPerDurabilityPoint(root); loadPricesPerDurabilityPoint(root);
//Load all enchantment prices //Load all enchantment prices
DataKey enchantmentCostNode = root.getRelative(GlobalBlacksmithSetting.ENCHANTMENT_COST.getParent()); DataKey enchantmentCostNode = root.getRelative(BlacksmithSetting.ENCHANTMENT_COST.getPath());
Map<String, String> relevantKeys = getRelevantKeys(enchantmentCostNode); Map<String, String> relevantKeys = getRelevantKeys(enchantmentCostNode);
for (String key : relevantKeys.keySet()) { for (String key : relevantKeys.keySet()) {
String enchantmentName = relevantKeys.get(key); String enchantmentName = relevantKeys.get(key);
@ -373,7 +350,7 @@ public class GlobalBlacksmithSettings {
* @param root <p>The configuration root node to search from</p> * @param root <p>The configuration root node to search from</p>
*/ */
private void loadPricesPerDurabilityPoint(DataKey root) { private void loadPricesPerDurabilityPoint(DataKey root) {
DataKey basePerDurabilityPriceNode = root.getRelative(GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT.getParent()); DataKey basePerDurabilityPriceNode = root.getRelative(BlacksmithSetting.PRICE_PER_DURABILITY_POINT.getPath());
Map<String, String> relevantKeys = getRelevantKeys(basePerDurabilityPriceNode); Map<String, String> relevantKeys = getRelevantKeys(basePerDurabilityPriceNode);
for (String key : relevantKeys.keySet()) { for (String key : relevantKeys.keySet()) {
@ -395,7 +372,7 @@ public class GlobalBlacksmithSettings {
* @param root <p>The configuration root node to search from</p> * @param root <p>The configuration root node to search from</p>
*/ */
private void loadBasePrices(DataKey root) { private void loadBasePrices(DataKey root) {
DataKey basePriceNode = root.getRelative(GlobalBlacksmithSetting.BASE_PRICE.getParent()); DataKey basePriceNode = root.getRelative(BlacksmithSetting.BASE_PRICE.getPath());
Map<String, String> relevantKeys = getRelevantKeys(basePriceNode); Map<String, String> relevantKeys = getRelevantKeys(basePriceNode);
for (String key : relevantKeys.keySet()) { for (String key : relevantKeys.keySet()) {
@ -474,32 +451,13 @@ public class GlobalBlacksmithSettings {
return normalizedName.toLowerCase().replace("_", "-"); return normalizedName.toLowerCase().replace("_", "-");
} }
/**
* Loads all default NPC settings
*
* @param root <p>The root node of all default NPC settings</p>
*/
private void loadDefaultNPCSettings(DataKey root) {
for (BlacksmithNPCSetting setting : BlacksmithNPCSetting.values()) {
if (!root.keyExists(setting.getPath())) {
//If the setting does not exist in the config file, add it
root.setRaw(setting.getPath(), setting.getDefaultValue());
} else {
//Set the setting to the value found in the path
defaultNPCSettings.put(setting, root.getRaw(setting.getPath()));
}
}
loadReforgeAbleItems();
loadEnchantmentBlocklist();
}
/** /**
* Loads reforgeAble items from the current value * Loads reforgeAble items from the current value
*/ */
private void loadReforgeAbleItems() { private void loadReforgeAbleItems() {
defaultReforgeAbleMaterials.clear(); defaultReforgeAbleMaterials.clear();
List<String> materialNames = ConfigHelper.asStringList(defaultNPCSettings.get( List<String> materialNames = ConfigHelper.asStringList(settings.get(
BlacksmithNPCSetting.REFORGE_ABLE_ITEMS)); BlacksmithSetting.REFORGE_ABLE_ITEMS));
if (materialNames != null) { if (materialNames != null) {
defaultReforgeAbleMaterials.addAll(BlacksmithNPCSettings.getReforgeAbleItems(materialNames)); defaultReforgeAbleMaterials.addAll(BlacksmithNPCSettings.getReforgeAbleItems(materialNames));
} }
@ -510,8 +468,8 @@ public class GlobalBlacksmithSettings {
*/ */
private void loadEnchantmentBlocklist() { private void loadEnchantmentBlocklist() {
defaultEnchantmentBlocklist.clear(); defaultEnchantmentBlocklist.clear();
List<String> enchantmentNames = ConfigHelper.asStringList(defaultNPCSettings.get( List<String> enchantmentNames = ConfigHelper.asStringList(settings.get(
BlacksmithNPCSetting.ENCHANTMENT_BLOCKLIST)); BlacksmithSetting.ENCHANTMENT_BLOCKLIST));
if (enchantmentNames != null) { if (enchantmentNames != null) {
defaultEnchantmentBlocklist.addAll(BlacksmithNPCSettings.getEnchantmentBlocklist(enchantmentNames)); defaultEnchantmentBlocklist.addAll(BlacksmithNPCSettings.getEnchantmentBlocklist(enchantmentNames));
} }
@ -522,30 +480,25 @@ public class GlobalBlacksmithSettings {
*/ */
private void save() { private void save() {
DataKey root = defaultConfig.getKey(""); DataKey root = defaultConfig.getKey("");
//Save all default NPC settings //Save all default settings
for (BlacksmithNPCSetting setting : BlacksmithNPCSetting.values()) { for (BlacksmithSetting setting : BlacksmithSetting.values()) {
root.setRaw(setting.getPath(), defaultNPCSettings.get(setting)); root.setRaw(setting.getPath(), settings.get(setting));
}
//Save all normal global settings
for (GlobalBlacksmithSetting globalBlacksmithSetting : GlobalBlacksmithSetting.values()) {
root.setRaw(globalBlacksmithSetting.getPath(), globalSettings.get(globalBlacksmithSetting));
} }
//Save all base prices //Save all base prices
DataKey basePriceNode = root.getRelative(GlobalBlacksmithSetting.BASE_PRICE.getParent()); DataKey basePriceNode = root.getRelative(BlacksmithSetting.BASE_PRICE.getPath());
for (Material material : materialBasePrices.keySet()) { for (Material material : materialBasePrices.keySet()) {
basePriceNode.setRaw(unNormalizeName(material.name()), materialBasePrices.get(material)); basePriceNode.setRaw(unNormalizeName(material.name()), materialBasePrices.get(material));
} }
//Save all per-durability-point prices //Save all per-durability-point prices
DataKey basePerDurabilityPriceNode = root.getRelative(GlobalBlacksmithSetting.PRICE_PER_DURABILITY_POINT.getParent()); DataKey basePerDurabilityPriceNode = root.getRelative(BlacksmithSetting.PRICE_PER_DURABILITY_POINT.getPath());
for (Material material : materialPricePerDurabilityPoints.keySet()) { for (Material material : materialPricePerDurabilityPoints.keySet()) {
basePerDurabilityPriceNode.setRaw(unNormalizeName(material.name()), materialPricePerDurabilityPoints.get(material)); basePerDurabilityPriceNode.setRaw(unNormalizeName(material.name()), materialPricePerDurabilityPoints.get(material));
} }
//Load all enchantment prices //Load all enchantment prices
DataKey enchantmentCostNode = root.getRelative(GlobalBlacksmithSetting.ENCHANTMENT_COST.getParent()); DataKey enchantmentCostNode = root.getRelative(BlacksmithSetting.ENCHANTMENT_COST.getPath());
for (Enchantment enchantment : enchantmentCosts.keySet()) { for (Enchantment enchantment : enchantmentCosts.keySet()) {
enchantmentCostNode.setRaw(unNormalizeName(enchantment.getKey().getKey()), enchantmentCosts.get(enchantment)); enchantmentCostNode.setRaw(unNormalizeName(enchantment.getKey().getKey()), enchantmentCosts.get(enchantment));
} }

View File

@ -1,75 +0,0 @@
package net.knarcraft.blacksmith.config.scrapper;
import net.knarcraft.blacksmith.config.GlobalSetting;
import net.knarcraft.blacksmith.config.SettingValueType;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
/**
* Settings which are the same for every scrapper
*/
public enum GlobalScrapperSetting implements GlobalSetting {
/**
* Whether to display exact time in minutes and seconds when displaying a remaining cool-down
*/
SHOW_EXACT_TIME("scrapper.global.showExactTime", SettingValueType.BOOLEAN, "false",
"showExactTime"),
/**
* Whether to give experience back when salvaging an enchanted item
*/
GIVE_EXPERIENCE("scrapper.global.giveExperience", SettingValueType.BOOLEAN, "true",
"giveExperience"),
;
private final String path;
private final String parent;
private final String commandName;
private final Object value;
private final SettingValueType valueType;
/**
* Instantiates a new setting
*
* @param path <p>The full config path for this setting</p>
* @param valueType <p>The type of value used by this setting</p>
* @param value <p>The default value of this setting</p>
* @param commandName <p>The name of the command used to change this setting</p>
*/
GlobalScrapperSetting(String path, SettingValueType valueType, Object value, String commandName) {
this.path = path;
this.value = value;
this.commandName = commandName;
this.valueType = valueType;
String[] pathParts = path.split("\\.");
this.parent = String.join(".", Arrays.copyOfRange(pathParts, 0, pathParts.length - 1));
}
@Override
public @NotNull String getPath() {
return path;
}
@Override
public @NotNull String getParent() {
return parent;
}
@Override
public @NotNull Object getDefaultValue() {
return value;
}
@Override
public @NotNull String getCommandName() {
return commandName;
}
@Override
public @NotNull SettingValueType getValueType() {
return this.valueType;
}
}

View File

@ -4,16 +4,16 @@ import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.YamlStorage; import net.citizensnpcs.api.util.YamlStorage;
import net.knarcraft.blacksmith.BlacksmithPlugin; import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.config.Settings;
import net.knarcraft.blacksmith.util.ConfigHelper; import net.knarcraft.blacksmith.util.ConfigHelper;
import java.io.File; import java.io.File;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class GlobalScrapperSettings { public class GlobalScrapperSettings implements Settings<ScrapperSetting> {
private final Map<ScrapperNPCSetting, Object> defaultNPCSettings = new HashMap<>(); private final Map<ScrapperSetting, Object> settings = new HashMap<>();
private final Map<GlobalScrapperSetting, Object> globalSettings = new HashMap<>();
private final YamlStorage defaultConfig; private final YamlStorage defaultConfig;
@ -37,14 +37,10 @@ public class GlobalScrapperSettings {
DataKey root = defaultConfig.getKey(""); DataKey root = defaultConfig.getKey("");
//Just in case, clear existing values //Just in case, clear existing values
defaultNPCSettings.clear(); settings.clear();
globalSettings.clear();
//Load/Save NPC default settings
loadDefaultNPCSettings(root);
//Load/Save global settings //Load/Save global settings
loadGlobalSettings(root); loadSettings(root);
//Save any modified values to disk //Save any modified values to disk
defaultConfig.save(); defaultConfig.save();
@ -53,27 +49,16 @@ public class GlobalScrapperSettings {
/** /**
* Changes the value of the given setting * Changes the value of the given setting
* *
* @param globalScrapperSetting <p>The global setting to change</p> * @param scrapperSetting <p>The default NPC setting to change</p>
* @param newValue <p>The new value of the setting</p>
*/
public void changeValue(GlobalScrapperSetting globalScrapperSetting, Object newValue) {
globalSettings.put(globalScrapperSetting, newValue);
save();
}
/**
* Changes the value of the given setting
*
* @param scrapperNPCSetting <p>The default NPC setting to change</p>
* @param newValue <p>The new value for the setting</p> * @param newValue <p>The new value for the setting</p>
*/ */
public void changeValue(ScrapperNPCSetting scrapperNPCSetting, Object newValue) { public void changeValue(ScrapperSetting scrapperSetting, Object newValue) {
if (scrapperNPCSetting.getValueType() == SettingValueType.STRING_LIST || if (scrapperSetting.getValueType() == SettingValueType.STRING_LIST ||
scrapperNPCSetting.getValueType() == SettingValueType.REFORGE_ABLE_ITEMS) { scrapperSetting.getValueType() == SettingValueType.REFORGE_ABLE_ITEMS) {
//Workaround to make sure it's treated as the correct type //Workaround to make sure it's treated as the correct type
defaultNPCSettings.put(scrapperNPCSetting, newValue == null ? null : ConfigHelper.asStringList(newValue)); settings.put(scrapperSetting, newValue == null ? null : ConfigHelper.asStringList(newValue));
} else { } else {
defaultNPCSettings.put(scrapperNPCSetting, newValue); settings.put(scrapperSetting, newValue);
} }
save(); save();
} }
@ -81,21 +66,11 @@ public class GlobalScrapperSettings {
/** /**
* Gets the current raw value of the given global setting * Gets the current raw value of the given global setting
* *
* @param globalBlacksmithSetting <p>The setting to get</p> * @param scrapperSetting <p>The setting to get</p>
* @return <p>The current raw setting value</p> * @return <p>The current raw setting value</p>
*/ */
public Object getRawValue(GlobalScrapperSetting globalBlacksmithSetting) { public Object getRawValue(ScrapperSetting scrapperSetting) {
return globalSettings.get(globalBlacksmithSetting); return settings.get(scrapperSetting);
}
/**
* Gets the current raw value of the given default NPC setting
*
* @param scrapperNPCSetting <p>The setting to get</p>
* @return <p>The current raw setting value</p>
*/
public Object getRawValue(ScrapperNPCSetting scrapperNPCSetting) {
return defaultNPCSettings.get(scrapperNPCSetting);
} }
/** /**
@ -103,8 +78,8 @@ public class GlobalScrapperSettings {
* *
* @return <p>The current value of the default NPC settings</p> * @return <p>The current value of the default NPC settings</p>
*/ */
public Map<ScrapperNPCSetting, Object> getDefaultNPCSettings() { public Map<ScrapperSetting, Object> getDefaultNPCSettings() {
return new HashMap<>(this.defaultNPCSettings); return new HashMap<>(this.settings);
} }
/** /**
@ -113,7 +88,7 @@ public class GlobalScrapperSettings {
* @return <p>Whether to show exact time</p> * @return <p>Whether to show exact time</p>
*/ */
public boolean getShowExactTime() { public boolean getShowExactTime() {
return asBoolean(GlobalScrapperSetting.SHOW_EXACT_TIME); return asBoolean(ScrapperSetting.SHOW_EXACT_TIME);
} }
/** /**
@ -124,7 +99,7 @@ public class GlobalScrapperSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as a boolean</p> * @return <p>The value of the given setting as a boolean</p>
*/ */
public boolean asBoolean(GlobalScrapperSetting setting) { public boolean asBoolean(ScrapperSetting setting) {
return ConfigHelper.asBoolean(getValue(setting)); return ConfigHelper.asBoolean(getValue(setting));
} }
@ -136,7 +111,7 @@ public class GlobalScrapperSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as a double</p> * @return <p>The value of the given setting as a double</p>
*/ */
public double asDouble(GlobalScrapperSetting setting) { public double asDouble(ScrapperSetting setting) {
return ConfigHelper.asDouble(getValue(setting)); return ConfigHelper.asDouble(getValue(setting));
} }
@ -146,8 +121,8 @@ public class GlobalScrapperSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The current value</p> * @return <p>The current value</p>
*/ */
private Object getValue(GlobalScrapperSetting setting) { private Object getValue(ScrapperSetting setting) {
Object value = globalSettings.get(setting); Object value = settings.get(setting);
//If not set in config.yml, use the default value from the enum //If not set in config.yml, use the default value from the enum
if (value == null) { if (value == null) {
value = setting.getDefaultValue(); value = setting.getDefaultValue();
@ -160,31 +135,14 @@ public class GlobalScrapperSettings {
* *
* @param root <p>The root node of all global settings</p> * @param root <p>The root node of all global settings</p>
*/ */
private void loadGlobalSettings(DataKey root) { private void loadSettings(DataKey root) {
for (GlobalScrapperSetting globalScrapperSetting : GlobalScrapperSetting.values()) { for (ScrapperSetting setting : ScrapperSetting.values()) {
if (!root.keyExists(globalScrapperSetting.getPath())) { if (!root.keyExists(setting.getChildPath())) {
//If the setting does not exist in the config file, add it //If the setting does not exist in the config file, add it
root.setRaw(globalScrapperSetting.getPath(), globalScrapperSetting.getDefaultValue()); root.setRaw(setting.getChildPath(), setting.getDefaultValue());
} else { } else {
//Set the setting to the value found in the path //Set the setting to the value found in the path
globalSettings.put(globalScrapperSetting, root.getRaw(globalScrapperSetting.getPath())); settings.put(setting, root.getRaw(setting.getChildPath()));
}
}
}
/**
* Loads all default NPC settings
*
* @param root <p>The root node of all default NPC settings</p>
*/
private void loadDefaultNPCSettings(DataKey root) {
for (ScrapperNPCSetting setting : ScrapperNPCSetting.values()) {
if (!root.keyExists(setting.getPath())) {
//If the setting does not exist in the config file, add it
root.setRaw(setting.getPath(), setting.getDefaultValue());
} else {
//Set the setting to the value found in the path
defaultNPCSettings.put(setting, root.getRaw(setting.getPath()));
} }
} }
} }
@ -194,14 +152,9 @@ public class GlobalScrapperSettings {
*/ */
private void save() { private void save() {
DataKey root = defaultConfig.getKey(""); DataKey root = defaultConfig.getKey("");
//Save all default NPC settings //Save all default settings
for (ScrapperNPCSetting setting : ScrapperNPCSetting.values()) { for (ScrapperSetting setting : ScrapperSetting.values()) {
root.setRaw(setting.getPath(), defaultNPCSettings.get(setting)); root.setRaw(setting.getPath(), settings.get(setting));
}
//Save all normal global settings
for (GlobalScrapperSetting globalBlacksmithSetting : GlobalScrapperSetting.values()) {
root.setRaw(globalBlacksmithSetting.getPath(), globalSettings.get(globalBlacksmithSetting));
} }
//Perform the actual save to disk //Perform the actual save to disk

View File

@ -2,17 +2,15 @@ package net.knarcraft.blacksmith.config.scrapper;
import net.citizensnpcs.api.util.DataKey; import net.citizensnpcs.api.util.DataKey;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.config.SmithPreset; import net.knarcraft.blacksmith.config.Settings;
import net.knarcraft.blacksmith.config.TraitSettings; import net.knarcraft.blacksmith.config.TraitSettings;
import net.knarcraft.blacksmith.util.ConfigHelper; import net.knarcraft.blacksmith.util.ConfigHelper;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
public class ScrapperNPCSettings implements TraitSettings { public class ScrapperNPCSettings implements TraitSettings, Settings<ScrapperSetting> {
private final Map<ScrapperNPCSetting, Object> currentValues = new HashMap<>(); private final Map<ScrapperSetting, Object> currentValues = new HashMap<>();
private final GlobalScrapperSettings globalScrapperSettings; private final GlobalScrapperSettings globalScrapperSettings;
/** /**
@ -30,7 +28,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @param key <p>The data key to load variables from</p> * @param key <p>The data key to load variables from</p>
*/ */
public void loadVariables(DataKey key) { public void loadVariables(DataKey key) {
for (ScrapperNPCSetting setting : ScrapperNPCSetting.values()) { for (ScrapperSetting setting : ScrapperSetting.values()) {
if (key.keyExists(setting.getChildPath())) { if (key.keyExists(setting.getChildPath())) {
currentValues.put(setting, key.getRaw(setting.getChildPath())); currentValues.put(setting, key.getRaw(setting.getChildPath()));
} }
@ -43,7 +41,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @param key <p>The data key to save variables to</p> * @param key <p>The data key to save variables to</p>
*/ */
public void saveVariables(DataKey key) { public void saveVariables(DataKey key) {
for (ScrapperNPCSetting setting : ScrapperNPCSetting.values()) { for (ScrapperSetting setting : ScrapperSetting.values()) {
key.setRaw(setting.getChildPath(), currentValues.get(setting)); key.setRaw(setting.getChildPath(), currentValues.get(setting));
} }
} }
@ -54,7 +52,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @param setting <p>The setting to change</p> * @param setting <p>The setting to change</p>
* @param newValue <p>The new value of the setting</p> * @param newValue <p>The new value of the setting</p>
*/ */
public void changeSetting(ScrapperNPCSetting setting, Object newValue) { public void changeValue(ScrapperSetting setting, Object newValue) {
if (setting.getValueType() == SettingValueType.STRING_LIST || if (setting.getValueType() == SettingValueType.STRING_LIST ||
setting.getValueType() == SettingValueType.REFORGE_ABLE_ITEMS) { setting.getValueType() == SettingValueType.REFORGE_ABLE_ITEMS) {
//Workaround to make sure it's treated as the correct type //Workaround to make sure it's treated as the correct type
@ -70,23 +68,23 @@ public class ScrapperNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The current value of the setting</p> * @return <p>The current value of the setting</p>
*/ */
public Object getRawValue(ScrapperNPCSetting setting) { public Object getRawValue(ScrapperSetting setting) {
return currentValues.get(setting); return currentValues.get(setting);
} }
@Override @Override
public String getBusyWithPlayerMessage() { public String getBusyWithPlayerMessage() {
return asString(ScrapperNPCSetting.BUSY_WITH_PLAYER_MESSAGE); return asString(ScrapperSetting.BUSY_WITH_PLAYER_MESSAGE);
} }
@Override @Override
public String getBusyWorkingMessage() { public String getBusyWorkingMessage() {
return asString(ScrapperNPCSetting.BUSY_WITH_SALVAGE_MESSAGE); return asString(ScrapperSetting.BUSY_WITH_SALVAGE_MESSAGE);
} }
@Override @Override
public String getStartWorkingMessage() { public String getStartWorkingMessage() {
return asString(ScrapperNPCSetting.START_SALVAGE_MESSAGE); return asString(ScrapperSetting.START_SALVAGE_MESSAGE);
} }
/** /**
@ -95,19 +93,19 @@ public class ScrapperNPCSettings implements TraitSettings {
* @return <p>The reforge success message</p> * @return <p>The reforge success message</p>
*/ */
public String getSuccessMessage() { public String getSuccessMessage() {
return asString(ScrapperNPCSetting.SUCCESS_SALVAGE_MESSAGE); return asString(ScrapperSetting.SUCCESS_SALVAGE_MESSAGE);
} }
@Override @Override
public String getCoolDownUnexpiredMessage() { public String getCoolDownUnexpiredMessage() {
return asString(ScrapperNPCSetting.COOL_DOWN_UNEXPIRED_MESSAGE); return asString(ScrapperSetting.COOL_DOWN_UNEXPIRED_MESSAGE);
} }
/** /**
* The message displayed if a player presents a different item after seeing the price to salvage an item * The message displayed if a player presents a different item after seeing the price to salvage an item
*/ */
public String getItemChangedMessage() { public String getItemChangedMessage() {
return asString(ScrapperNPCSetting.ITEM_UNEXPECTEDLY_CHANGED_MESSAGE); return asString(ScrapperSetting.ITEM_UNEXPECTEDLY_CHANGED_MESSAGE);
} }
/** /**
@ -116,7 +114,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @return <p>The minimum salvage delay</p> * @return <p>The minimum salvage delay</p>
*/ */
public int getMinSalvageDelay() { public int getMinSalvageDelay() {
return asInt(ScrapperNPCSetting.MIN_SALVAGE_DELAY); return asInt(ScrapperSetting.MIN_SALVAGE_DELAY);
} }
/** /**
@ -125,7 +123,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @return <p>The maximum salvage delay</p> * @return <p>The maximum salvage delay</p>
*/ */
public int getMaxSalvageDelay() { public int getMaxSalvageDelay() {
return asInt(ScrapperNPCSetting.MAX_SALVAGE_DELAY); return asInt(ScrapperSetting.MAX_SALVAGE_DELAY);
} }
/** /**
@ -134,7 +132,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @return <p>The salvage cool-down</p> * @return <p>The salvage cool-down</p>
*/ */
public int getSalvageCoolDown() { public int getSalvageCoolDown() {
return asInt(ScrapperNPCSetting.SALVAGE_COOL_DOWN); return asInt(ScrapperSetting.SALVAGE_COOL_DOWN);
} }
/** /**
@ -143,12 +141,12 @@ public class ScrapperNPCSettings implements TraitSettings {
* @return <p>Whether to drop reforged items on the ground</p> * @return <p>Whether to drop reforged items on the ground</p>
*/ */
public boolean getDropItem() { public boolean getDropItem() {
return asBoolean(ScrapperNPCSetting.DROP_ITEM); return asBoolean(ScrapperSetting.DROP_ITEM);
} }
@Override @Override
public boolean getDisableCoolDown() { public boolean getDisableCoolDown() {
return asInt(ScrapperNPCSetting.SALVAGE_COOL_DOWN) <= 0; return asInt(ScrapperSetting.SALVAGE_COOL_DOWN) <= 0;
} }
/** /**
@ -157,7 +155,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @return <p>Whether to disable the reforge delay</p> * @return <p>Whether to disable the reforge delay</p>
*/ */
public boolean getDisableDelay() { public boolean getDisableDelay() {
return asInt(ScrapperNPCSetting.MAX_SALVAGE_DELAY) <= 0; return asInt(ScrapperSetting.MAX_SALVAGE_DELAY) <= 0;
} }
/** /**
@ -168,7 +166,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as an integer</p> * @return <p>The value of the given setting as an integer</p>
*/ */
private int asInt(ScrapperNPCSetting setting) { private int asInt(ScrapperSetting setting) {
return ConfigHelper.asInt(getValue(setting)); return ConfigHelper.asInt(getValue(setting));
} }
@ -178,7 +176,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as a string</p> * @return <p>The value of the given setting as a string</p>
*/ */
private String asString(ScrapperNPCSetting setting) { private String asString(ScrapperSetting setting) {
return getValue(setting).toString(); return getValue(setting).toString();
} }
@ -188,7 +186,7 @@ public class ScrapperNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The value of the given setting as a boolean</p> * @return <p>The value of the given setting as a boolean</p>
*/ */
private boolean asBoolean(ScrapperNPCSetting setting) { private boolean asBoolean(ScrapperSetting setting) {
return ConfigHelper.asBoolean(getValue(setting)); return ConfigHelper.asBoolean(getValue(setting));
} }
@ -198,11 +196,11 @@ public class ScrapperNPCSettings implements TraitSettings {
* @param setting <p>The setting to get the value of</p> * @param setting <p>The setting to get the value of</p>
* @return <p>The current value</p> * @return <p>The current value</p>
*/ */
private Object getValue(ScrapperNPCSetting setting) { private Object getValue(ScrapperSetting setting) {
Object value = currentValues.get(setting); Object value = currentValues.get(setting);
//If not set, use the default value from the config.yml file //If not set, use the default value from the config.yml file
if (value == null) { if (value == null) {
Map<ScrapperNPCSetting, Object> defaultNPCSettings = globalScrapperSettings.getDefaultNPCSettings(); Map<ScrapperSetting, Object> defaultNPCSettings = globalScrapperSettings.getDefaultNPCSettings();
if (defaultNPCSettings.containsKey(setting)) { if (defaultNPCSettings.containsKey(setting)) {
value = defaultNPCSettings.get(setting); value = defaultNPCSettings.get(setting);
} }
@ -214,26 +212,4 @@ public class ScrapperNPCSettings implements TraitSettings {
return value; return value;
} }
/**
* Replaces placeholders in the given reforge-able value
*
* @param stringList <p>The value specified by a user</p>
* @return <p>The value with placeholders replaced</p>
*/
private static List<String> replaceReforgeAblePresets(List<String> stringList) {
List<String> newStrings = new ArrayList<>();
for (String item : stringList) {
if (item == null) {
continue;
}
String replaced = SmithPreset.replacePreset(item);
if (!replaced.equals(item)) {
newStrings.addAll(List.of(replaced.split(",")));
} else {
newStrings.add(item);
}
}
return newStrings;
}
} }

View File

@ -1,42 +1,49 @@
package net.knarcraft.blacksmith.config.scrapper; package net.knarcraft.blacksmith.config.scrapper;
import net.knarcraft.blacksmith.config.NPCSetting; import net.knarcraft.blacksmith.config.Setting;
import net.knarcraft.blacksmith.config.SettingValueType; import net.knarcraft.blacksmith.config.SettingValueType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public enum ScrapperNPCSetting implements NPCSetting { public enum ScrapperSetting implements Setting {
/** /**
* The setting for whether the NPC should drop an item to the ground when finished * The setting for whether the NPC should drop an item to the ground when finished
* *
* <p>If set to false, the item will be directly put in the player's inventory instead</p> * <p>If set to false, the item will be directly put in the player's inventory instead</p>
*/ */
DROP_ITEM("dropItem", SettingValueType.BOOLEAN, true, "dropItem"), DROP_ITEM("dropItem", SettingValueType.BOOLEAN, true, "dropItem",
true, false),
/** /**
* The chance of a scrapper returning no salvage, regardless of item condition * The chance of a scrapper returning no salvage, regardless of item condition
*/ */
FAIL_SALVAGE_CHANCE("failSalvageChance", SettingValueType.POSITIVE_DOUBLE, 0, "failSalvageChance"), FAIL_SALVAGE_CHANCE("failSalvageChance", SettingValueType.POSITIVE_DOUBLE, 0,
"failSalvageChance", true, false),
/** /**
* The setting for which items a scrapper is able to salvage * The setting for which items a scrapper is able to salvage
*/ */
SALVAGE_ABLE_ITEMS("salvageAbleItems", SettingValueType.REFORGE_ABLE_ITEMS, "", "salvageAbleItems"), SALVAGE_ABLE_ITEMS("salvageAbleItems", SettingValueType.REFORGE_ABLE_ITEMS, "",
"salvageAbleItems", true, false),
/** /**
* The maximum amount of seconds a player may need to wait for the reforging to finish * The maximum amount of seconds a player may need to wait for the reforging to finish
*/ */
MAX_SALVAGE_DELAY("delaysInSeconds.maximum", SettingValueType.POSITIVE_INTEGER, 30, "maxReforgeDelay"), MAX_SALVAGE_DELAY("delaysInSeconds.maximum", SettingValueType.POSITIVE_INTEGER, 30,
"maxReforgeDelay", true, false),
/** /**
* The minimum amount of seconds a player may need to wait for the reforging to finish * The minimum amount of seconds a player may need to wait for the reforging to finish
*/ */
MIN_SALVAGE_DELAY("delaysInSeconds.minimum", SettingValueType.POSITIVE_INTEGER, 5, "minReforgeDelay"), MIN_SALVAGE_DELAY("delaysInSeconds.minimum", SettingValueType.POSITIVE_INTEGER, 5,
"minReforgeDelay", true, false),
/** /**
* The setting for number of seconds a player has to wait between each usage of the blacksmith * The setting for number of seconds a player has to wait between each usage of the blacksmith
*/ */
SALVAGE_COOL_DOWN("delaysInSeconds.reforgeCoolDown", SettingValueType.POSITIVE_INTEGER, 60, "reforgeCoolDown"), SALVAGE_COOL_DOWN("delaysInSeconds.reforgeCoolDown", SettingValueType.POSITIVE_INTEGER, 60,
"reforgeCoolDown", true, false),
/*----------- /*-----------
| Messages | | Messages |
@ -46,51 +53,70 @@ public enum ScrapperNPCSetting implements NPCSetting {
* The message displayed when the scrapper is busy with another player * The message displayed when the scrapper is busy with another player
*/ */
BUSY_WITH_PLAYER_MESSAGE("messages.busyPlayerMessage", SettingValueType.STRING, BUSY_WITH_PLAYER_MESSAGE("messages.busyPlayerMessage", SettingValueType.STRING,
"&cI'm busy at the moment. Come back later!", "busyPlayerMessage"), "&cI'm busy at the moment. Come back later!", "busyPlayerMessage",
true, true),
/** /**
* The message displayed when the scrapper is busy salvaging the player's item * The message displayed when the scrapper is busy salvaging the player's item
*/ */
BUSY_WITH_SALVAGE_MESSAGE("messages.busySalvageMessage", SettingValueType.STRING, BUSY_WITH_SALVAGE_MESSAGE("messages.busySalvageMessage", SettingValueType.STRING,
"&cI'm working on it. Be patient! I'll finish {time}!", "busySalvageMessage"), "&cI'm working on it. Be patient! I'll finish {time}!", "busySalvageMessage",
true, true),
/** /**
* The message displayed if the player needs to wait for the cool-down to expire * The message displayed if the player needs to wait for the cool-down to expire
*/ */
COOL_DOWN_UNEXPIRED_MESSAGE("messages.coolDownUnexpiredMessage", SettingValueType.STRING, COOL_DOWN_UNEXPIRED_MESSAGE("messages.coolDownUnexpiredMessage", SettingValueType.STRING,
"&cYou've already had your chance! Give me a break! I'll be ready {time}!", "&cYou've already had your chance! Give me a break! I'll be ready {time}!",
"coolDownUnexpiredMessage"), "coolDownUnexpiredMessage", true, true),
/** /**
* The message displayed if presented with an item that cannot be salvaged by the NPC * The message displayed if presented with an item that cannot be salvaged by the NPC
*/ */
CANNOT_SALVAGE_MESSAGE("messages.cannotSalvageMessage", SettingValueType.STRING, CANNOT_SALVAGE_MESSAGE("messages.cannotSalvageMessage", SettingValueType.STRING,
"&cI'm unable to salvage that item", "cannotSalvageMessage"), "&cI'm unable to salvage that item", "cannotSalvageMessage", true, true),
/** /**
* The message displayed if salvaging an item would return in no items * The message displayed if salvaging an item would return in no items
*/ */
TOO_DAMAGED_FOR_SALVAGE_MESSAGE("messages.tooDamagedForSalvageMessage", SettingValueType.STRING, TOO_DAMAGED_FOR_SALVAGE_MESSAGE("messages.tooDamagedForSalvageMessage", SettingValueType.STRING,
"&cThat item is too damaged to be salvaged into anything useful", "&cThat item is too damaged to be salvaged into anything useful",
"tooDamagedForSalvageMessage"), "tooDamagedForSalvageMessage", true, true),
/** /**
* The message displayed if a salvage is successful * The message displayed if a salvage is successful
*/ */
SUCCESS_SALVAGE_MESSAGE("messages.successSalvagedMessage", SettingValueType.STRING, "&cThere you go!", SUCCESS_SALVAGE_MESSAGE("messages.successSalvagedMessage", SettingValueType.STRING, "&cThere you go!",
"successSalvagedMessage"), "successSalvagedMessage", true, true),
/** /**
* The message displayed if a player presents a different item after seeing the price to reforge an item * The message displayed if a player presents a different item after seeing the price to reforge an item
*/ */
ITEM_UNEXPECTEDLY_CHANGED_MESSAGE("messages.itemChangedMessage", SettingValueType.STRING, ITEM_UNEXPECTEDLY_CHANGED_MESSAGE("messages.itemChangedMessage", SettingValueType.STRING,
"&cThat's not the item you wanted to reforge before!", "itemChangedMessage"), "&cThat's not the item you wanted to reforge before!", "itemChangedMessage",
true, true),
/** /**
* The message displayed when the scrapper starts salvaging an item * The message displayed when the scrapper starts salvaging an item
*/ */
START_SALVAGE_MESSAGE("messages.startSalvageMessage", SettingValueType.STRING, START_SALVAGE_MESSAGE("messages.startSalvageMessage", SettingValueType.STRING,
"&eOk, let's see what I can do...", "startSalvageMessage"), "&eOk, let's see what I can do...", "startSalvageMessage", true, true),
/*------------------
| Global settings |
------------------*/
/**
* Whether to display exact time in minutes and seconds when displaying a remaining cool-down
*/
SHOW_EXACT_TIME("scrapper.global.showExactTime", SettingValueType.BOOLEAN, "false",
"showExactTime", false, false),
/**
* Whether to give experience back when salvaging an enchanted item
*/
GIVE_EXPERIENCE("scrapper.global.giveExperience", SettingValueType.BOOLEAN, "true",
"giveExperience", false, false),
; ;
private final String path; private final String path;
@ -98,6 +124,8 @@ public enum ScrapperNPCSetting implements NPCSetting {
private final Object value; private final Object value;
private final String commandName; private final String commandName;
private final SettingValueType valueType; private final SettingValueType valueType;
private final boolean isPerNPC;
private final boolean isMessage;
/** /**
* Instantiates a new setting * Instantiates a new setting
@ -106,13 +134,22 @@ public enum ScrapperNPCSetting implements NPCSetting {
* @param valueType <p>The type of value used by this setting</p> * @param valueType <p>The type of value used by this setting</p>
* @param value <p>The default value of this setting</p> * @param value <p>The default value of this setting</p>
* @param commandName <p>The name of the command used to change this setting</p> * @param commandName <p>The name of the command used to change this setting</p>
* @param isPerNPC <p>Whether this setting is per-NPC or global</p>
* @param isMessage <p>Whether this option is for an NPC message</p>
*/ */
ScrapperNPCSetting(String path, SettingValueType valueType, Object value, String commandName) { ScrapperSetting(String path, SettingValueType valueType, Object value, String commandName, boolean isPerNPC,
boolean isMessage) {
if (isPerNPC) {
this.path = "scrapper.defaults." + path; this.path = "scrapper.defaults." + path;
} else {
this.path = "scrapper.global." + path;
}
this.value = value; this.value = value;
this.valueType = valueType; this.valueType = valueType;
this.childPath = path; this.childPath = path;
this.commandName = commandName; this.commandName = commandName;
this.isPerNPC = isPerNPC;
this.isMessage = isMessage;
} }
@Override @Override
@ -140,4 +177,29 @@ public enum ScrapperNPCSetting implements NPCSetting {
return this.valueType; return this.valueType;
} }
@Override
public boolean isPerNPC() {
return this.isPerNPC;
}
@Override
public boolean isMessage() {
return this.isMessage;
}
/**
* Gets the scrapper setting specified by the input string
*
* @param input <p>The input to check</p>
* @return <p>The matching scrapper setting, or null if not found</p>
*/
public static @Nullable ScrapperSetting getSetting(@NotNull String input) {
for (ScrapperSetting scrapperSetting : ScrapperSetting.values()) {
if (input.equalsIgnoreCase(scrapperSetting.commandName)) {
return scrapperSetting;
}
}
return null;
}
} }

View File

@ -0,0 +1,81 @@
package net.knarcraft.blacksmith.util;
import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.config.Setting;
import net.knarcraft.blacksmith.config.SettingValueType;
import net.knarcraft.blacksmith.config.Settings;
import net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import static net.knarcraft.blacksmith.formatting.BlacksmithTranslatableMessage.getValueChangedMessage;
/**
* A helper class for the configuration command
*/
public final class ConfigCommandHelper {
private ConfigCommandHelper() {
}
/**
* Changes the value of the setting defined in the user's input
*
* @param args <p>The arguments given by the user</p>
* @param detectedSetting <p>The setting recognized from the input, if any</p>
* @param settings <p>The global settings object to get settings from</p>
* @param sender <p>The command sender to display any output to</p>
*/
public static <K extends Setting> void changeValue(@NotNull String[] args,
@NotNull K detectedSetting,
@NotNull Settings<K> settings,
@NotNull CommandSender sender) {
String newValue = args[1];
//This makes sure all arguments are treated as a sentence
if (detectedSetting.getValueType() == SettingValueType.STRING) {
newValue = String.join(" ", Arrays.asList(args).subList(1, args.length));
}
settings.changeValue(detectedSetting, newValue);
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
getValueChangedMessage(detectedSetting.getCommandName(), newValue));
}
/**
* Displays the current value of the selected setting
*
* @param setting <p>The global setting recognized from the input</p>
* @param settings <p>The global settings object to get settings from</p>
* @param sender <p>The command sender to display any output to</p>
*/
public static <K extends Setting> void displayCurrentValue(@NotNull K setting,
@NotNull Settings<K> settings,
@NotNull CommandSender sender) {
String settingValue;
String correctCommandName;
boolean printRawValue = false;
//Find the value of the specified setting
settingValue = String.valueOf(settings.getRawValue(setting));
correctCommandName = setting.getCommandName();
//For messages, print an additional raw value showing which color codes are used
if (setting.isPerNPC() && setting.isMessage()) {
printRawValue = true;
}
//Display the current value of the setting
BlacksmithPlugin.getStringFormatter().displaySuccessMessage(sender,
BlacksmithTranslatableMessage.getCurrentValueMessage(correctCommandName, settingValue));
//Print the value with any colors displayed as &a-f0-9
if (printRawValue) {
sender.sendMessage(BlacksmithTranslatableMessage.getRawValueMessage(
settingValue.replace(ChatColor.COLOR_CHAR, '&')));
}
}
}