Updated settings manager and economy handler.

This commit is contained in:
Brianna 2019-07-25 00:19:36 -04:00
parent f5e2f4562c
commit 222d6f2577
11 changed files with 620 additions and 260 deletions

11
pom.xml
View File

@ -79,5 +79,16 @@
<version>2.3.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.black_ixx</groupId>
<artifactId>playerpoints</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>net.tnemc</groupId>
<artifactId>Reserve</artifactId>
<version>0.1.3.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -4,16 +4,22 @@ import com.songoda.ultimaterepairing.anvil.AnvilManager;
import com.songoda.ultimaterepairing.anvil.UAnvil;
import com.songoda.ultimaterepairing.anvil.editor.Editor;
import com.songoda.ultimaterepairing.command.CommandManager;
import com.songoda.ultimaterepairing.listeners.BlockListeners;
import com.songoda.ultimaterepairing.listeners.InteractListeners;
import com.songoda.ultimaterepairing.listeners.InventoryListeners;
import com.songoda.ultimaterepairing.listeners.PlayerListeners;
import com.songoda.ultimaterepairing.economy.Economy;
import com.songoda.ultimaterepairing.economy.PlayerPointsEconomy;
import com.songoda.ultimaterepairing.economy.ReserveEconomy;
import com.songoda.ultimaterepairing.economy.VaultEconomy;
import com.songoda.ultimaterepairing.handlers.ParticleHandler;
import com.songoda.ultimaterepairing.handlers.RepairHandler;
import com.songoda.ultimaterepairing.hologram.Hologram;
import com.songoda.ultimaterepairing.hologram.HologramHolographicDisplays;
import com.songoda.ultimaterepairing.listeners.BlockListeners;
import com.songoda.ultimaterepairing.listeners.InteractListeners;
import com.songoda.ultimaterepairing.listeners.InventoryListeners;
import com.songoda.ultimaterepairing.listeners.PlayerListeners;
import com.songoda.ultimaterepairing.utils.*;
import com.songoda.ultimaterepairing.utils.locale.Locale;
import com.songoda.ultimaterepairing.utils.settings.Setting;
import com.songoda.ultimaterepairing.utils.settings.SettingsManager;
import com.songoda.ultimaterepairing.utils.updateModules.LocaleModule;
import com.songoda.update.Plugin;
import com.songoda.update.SongodaUpdate;
@ -21,11 +27,10 @@ import org.apache.commons.lang.ArrayUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public final class UltimateRepairing extends JavaPlugin implements Listener {
public class UltimateRepairing extends JavaPlugin {
private static CommandSender console = Bukkit.getConsoleSender();
private static UltimateRepairing INSTANCE;
@ -42,6 +47,7 @@ public final class UltimateRepairing extends JavaPlugin implements Listener {
private AnvilManager anvilManager;
private Hologram hologram;
private Economy economy;
private Editor editor;
@ -56,11 +62,9 @@ public final class UltimateRepairing extends JavaPlugin implements Listener {
console.sendMessage(Methods.formatText("&a============================="));
console.sendMessage(Methods.formatText("&7UltimateRepairing " + this.getDescription().getVersion() + " by &5Brianna <3!"));
console.sendMessage(Methods.formatText("&7Action: &aEnabling&7..."));
Bukkit.getPluginManager().registerEvents(this, this);
settingsManager = new SettingsManager(this);
settingsManager.updateSettings();
setupConfig();
this.settingsManager = new SettingsManager(this);
this.settingsManager.setupConfig();
new Locale(this, "en_US");
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode"));
@ -70,6 +74,16 @@ public final class UltimateRepairing extends JavaPlugin implements Listener {
plugin.addModule(new LocaleModule());
SongodaUpdate.load(plugin);
PluginManager pluginManager = getServer().getPluginManager();
// Setup Economy
if (Setting.VAULT_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("Vault"))
this.economy = new VaultEconomy();
else if (Setting.RESERVE_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("Reserve"))
this.economy = new ReserveEconomy();
else if (Setting.PLAYER_POINTS_ECONOMY.getBoolean() && pluginManager.isPluginEnabled("PlayerPoints"))
this.economy = new PlayerPointsEconomy();
this.editor = new Editor(this);
this.anvilManager = new AnvilManager();
@ -77,8 +91,6 @@ public final class UltimateRepairing extends JavaPlugin implements Listener {
this.commandManager = new CommandManager(this);
new ParticleHandler(this);
PluginManager pluginManager = getServer().getPluginManager();
// Register Hologram Plugin
if (pluginManager.isPluginEnabled("HolographicDisplays"))
hologram = new HologramHolographicDisplays(this);
@ -130,6 +142,7 @@ public final class UltimateRepairing extends JavaPlugin implements Listener {
public boolean isServerVersion(ServerVersion version) {
return serverVersion == version;
}
public boolean isServerVersion(ServerVersion... versions) {
return ArrayUtils.contains(versions, serverVersion);
}
@ -146,12 +159,12 @@ public final class UltimateRepairing extends JavaPlugin implements Listener {
dataFile.getConfig().set("data", null);
if (anvilManager.getAnvils() == null) return;
/*
* Save anvils from AnvilManager to Configuration.
*/
for (UAnvil anvil : anvilManager.getAnvils()) {
if (!anvil.shouldSave())continue;
if (!anvil.shouldSave()) continue;
String locationStr = Methods.serializeLocation(anvil.getLocation());
dataFile.getConfig().set("data." + locationStr + ".hologram", anvil.isHologram());
dataFile.getConfig().set("data." + locationStr + ".particles", anvil.isParticles());
@ -163,20 +176,11 @@ public final class UltimateRepairing extends JavaPlugin implements Listener {
dataFile.saveConfig();
}
private void setupConfig() {
try {
settingsManager.updateSettings();
getConfig().options().copyDefaults(true);
saveConfig();
} catch (Exception ex) {
Debugger.runReport(ex);
}
}
public void reload() {
try {
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode"));
this.locale.reloadMessages();
this.settingsManager.reloadConfig();
reloadConfig();
saveConfig();
} catch (Exception ex) {
@ -188,6 +192,10 @@ public final class UltimateRepairing extends JavaPlugin implements Listener {
return locale;
}
public Economy getEconomy() {
return economy;
}
public Editor getEditor() {
return editor;
}

View File

@ -0,0 +1,12 @@
package com.songoda.ultimaterepairing.economy;
import org.bukkit.OfflinePlayer;
public interface Economy {
boolean hasBalance(OfflinePlayer player, double cost);
boolean withdrawBalance(OfflinePlayer player, double cost);
boolean deposit(OfflinePlayer player, double amount);
}

View File

@ -0,0 +1,38 @@
package com.songoda.ultimaterepairing.economy;
import org.black_ixx.playerpoints.PlayerPoints;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
public class PlayerPointsEconomy implements Economy {
private final PlayerPoints playerPoints;
public PlayerPointsEconomy() {
this.playerPoints = (PlayerPoints) Bukkit.getServer().getPluginManager().getPlugin("PlayerPoints");
}
private int convertAmount(double amount) {
return (int) Math.ceil(amount);
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);
return playerPoints.getAPI().look(player.getUniqueId()) >= amount;
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);
return playerPoints.getAPI().take(player.getUniqueId(), amount);
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
int amt = convertAmount(amount);
return playerPoints.getAPI().give(player.getUniqueId(), amt);
}
}

View File

@ -0,0 +1,32 @@
package com.songoda.ultimaterepairing.economy;
import net.tnemc.core.Reserve;
import net.tnemc.core.economy.EconomyAPI;
import org.bukkit.OfflinePlayer;
import java.math.BigDecimal;
public class ReserveEconomy implements Economy {
EconomyAPI economyAPI;
public ReserveEconomy() {
if (Reserve.instance().economyProvided())
economyAPI = Reserve.instance().economy();
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
return economyAPI.hasHoldings(player.getUniqueId(), new BigDecimal(cost));
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
return economyAPI.removeHoldings(player.getUniqueId(), new BigDecimal(cost));
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
return economyAPI.addHoldings(player.getUniqueId(), new BigDecimal(amount));
}
}

View File

@ -0,0 +1,28 @@
package com.songoda.ultimaterepairing.economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
public class VaultEconomy implements Economy {
private final net.milkbowl.vault.economy.Economy vault;
public VaultEconomy() {
this.vault = Bukkit.getServicesManager().
getRegistration(net.milkbowl.vault.economy.Economy.class).getProvider();
}
@Override
public boolean hasBalance(OfflinePlayer player, double cost) {
return vault.has(player, cost);
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
return vault.withdrawPlayer(player, cost).transactionSuccess();
}
@Override
public boolean deposit(OfflinePlayer player, double amount) {
return vault.depositPlayer(player, amount).transactionSuccess();
}
}

View File

@ -6,7 +6,6 @@ import com.songoda.ultimaterepairing.anvil.PlayerAnvilData.RepairType;
import com.songoda.ultimaterepairing.utils.Debugger;
import com.songoda.ultimaterepairing.utils.Methods;
import com.songoda.ultimaterepairing.utils.ServerVersion;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.*;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
@ -14,7 +13,6 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.util.Vector;
import java.util.ArrayList;
@ -269,18 +267,14 @@ public class RepairHandler {
RepairType type = playerData.getType();
ItemStack players = playerData.getToBeRepaired();
boolean economy = false;
boolean sold = false;
if (instance.getServer().getPluginManager().getPlugin("Vault") != null && type == RepairType.ECONOMY) {
RegisteredServiceProvider<Economy> rsp = instance.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
net.milkbowl.vault.economy.Economy econ = rsp.getProvider();
if (type == RepairType.ECONOMY && instance.getEconomy() != null) {
int price = playerData.getPrice();
if (econ.has(player, price)) {
econ.withdrawPlayer(player, price);
if (instance.getEconomy().hasBalance(player, price)) {
instance.getEconomy().withdrawBalance(player, price);
sold = true;
}
economy = true;
}
int cost = Methods.getCost(type, players);
@ -355,12 +349,9 @@ public class RepairHandler {
}
if (type == RepairType.ECONOMY) {
if (!economy)
player.sendMessage("Vault is not installed.");
else
instance.getLocale().getMessage("event.repair.notenough")
.processPlaceholder("type", instance.getLocale().getMessage("interface.repair.eco").getMessage())
.sendPrefixedMessage(player);
instance.getLocale().getMessage("event.repair.notenough")
.processPlaceholder("type", instance.getLocale().getMessage("interface.repair.eco").getMessage())
.sendPrefixedMessage(player);
} else if (type == RepairType.XP)
instance.getLocale().getMessage("event.repair.notenough")
.processPlaceholder("type", instance.getLocale().getMessage("interface.repair.xp").getMessage())

View File

@ -1,221 +0,0 @@
package com.songoda.ultimaterepairing.utils;
import com.songoda.ultimaterepairing.UltimateRepairing;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by songoda on 6/4/2017.
*/
public class SettingsManager implements Listener {
private static final Pattern SETTINGS_PATTERN = Pattern.compile("(.{1,28}(?:\\s|$))|(.{0,28})", Pattern.DOTALL);
private final UltimateRepairing instance;
private String pluginName = "UltimateRepairing";
private Map<Player, String> cat = new HashMap<>();
private Map<Player, String> current = new HashMap<>();
public SettingsManager(UltimateRepairing plugin) {
this.instance = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
ItemStack clickedItem = event.getCurrentItem();
if (event.getInventory() != event.getWhoClicked().getOpenInventory().getTopInventory()
|| clickedItem == null || !clickedItem.hasItemMeta()
|| !clickedItem.getItemMeta().hasDisplayName()) {
return;
}
if (event.getView().getTitle().equals(Methods.formatTitle(pluginName + " Settings Manager"))) {
event.setCancelled(true);
if (clickedItem.getType().name().contains("STAINED_GLASS")) return;
String type = ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName());
this.cat.put((Player) event.getWhoClicked(), type);
this.openEditor((Player) event.getWhoClicked());
} else if (event.getView().getTitle().equals(Methods.formatTitle(pluginName + " Settings Editor"))) {
event.setCancelled(true);
if (clickedItem.getType().name().contains("STAINED_GLASS")) return;
Player player = (Player) event.getWhoClicked();
String key = cat.get(player) + "." + ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName());
if (instance.getConfig().get(key).getClass().getName().equals("java.lang.Boolean")) {
this.instance.getConfig().set(key, !instance.getConfig().getBoolean(key));
this.finishEditing(player);
} else {
this.editObject(player, key);
}
}
}
@EventHandler
public void onChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
if (!current.containsKey(player)) return;
String value = current.get(player);
FileConfiguration config = instance.getConfig();
if (config.isInt(value)) {
config.set(value, Integer.parseInt(event.getMessage()));
} else if (config.isDouble(value)) {
config.set(value, Double.parseDouble(event.getMessage()));
} else if (config.isString(value)) {
config.set(value, event.getMessage());
}
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () ->
this.finishEditing(player), 0L);
event.setCancelled(true);
}
private void finishEditing(Player player) {
this.current.remove(player);
this.instance.saveConfig();
this.openEditor(player);
}
private void editObject(Player player, String current) {
this.current.put(player, ChatColor.stripColor(current));
player.closeInventory();
player.sendMessage("");
player.sendMessage(Methods.formatText("&7Please enter a value for &6" + current + "&7."));
if (instance.getConfig().isInt(current) || instance.getConfig().isDouble(current)) {
player.sendMessage(Methods.formatText("&cUse only numbers."));
}
player.sendMessage("");
}
public void openSettingsManager(Player player) {
Inventory inventory = Bukkit.createInventory(null, 27, Methods.formatTitle(pluginName + " Settings Manager"));
ItemStack glass = Methods.getGlass();
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, glass);
}
int slot = 10;
for (String key : instance.getConfig().getDefaultSection().getKeys(false)) {
ItemStack item = new ItemStack(instance.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.WHITE_WOOL : Material.valueOf("WOOL"), 1, (byte) (slot - 9)); //ToDo: Make this function as it was meant to.
ItemMeta meta = item.getItemMeta();
meta.setLore(Collections.singletonList(Methods.formatText("&6Click To Edit This Category.")));
meta.setDisplayName(Methods.formatText("&f&l" + key));
item.setItemMeta(meta);
inventory.setItem(slot, item);
slot++;
}
player.openInventory(inventory);
}
private void openEditor(Player player) {
Inventory inventory = Bukkit.createInventory(null, 54, Methods.formatTitle(pluginName + " Settings Editor"));
FileConfiguration config = instance.getConfig();
int slot = 0;
for (String key : config.getConfigurationSection(cat.get(player)).getKeys(true)) {
String fKey = cat.get(player) + "." + key;
ItemStack item = new ItemStack(Material.DIAMOND_HELMET);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(Methods.formatText("&6" + key));
List<String> lore = new ArrayList<>();
if (config.isBoolean(fKey)) {
item.setType(Material.LEVER);
lore.add(Methods.formatText(config.getBoolean(fKey) ? "&atrue" : "&cfalse"));
} else if (config.isString(fKey)) {
item.setType(Material.PAPER);
lore.add(Methods.formatText("&9" + config.getString(fKey)));
} else if (config.isInt(fKey)) {
item.setType(instance.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&5" + config.getInt(fKey)));
}
meta.setLore(lore);
item.setItemMeta(meta);
inventory.setItem(slot, item);
slot++;
}
player.openInventory(inventory);
}
public void updateSettings() {
FileConfiguration config = instance.getConfig();
for (Setting setting : Setting.values()) {
config.addDefault(setting.setting, setting.option);
}
}
public enum Setting {
o1("Timeout", "Main.Time Before Repair Auto Canceled", 200L),
o2("XP-Cost-Equation", "Main.Experience Cost Equation", "{MaxDurability} - ({MaxDurability} - {Durability} / 40) + 1"),
o3("ECO-Cost-Equation", "Main.Economy Cost Equation", "{XPCost} * 5"),
o4("ITEM-Cost-Equation", "Main.Item Cost Equation", "{XPCost} * 3"),
o5("Enchanted-Item-Multiplier", "Main.Cost Multiplier For Enchanted Items", 2),
o6("ECO-Icon", "Interfaces.Economy Icon", UltimateRepairing.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "SUNFLOWER" : "DOUBLE_PLANT"),
o7("XP-Icon", "Interfaces.XP Icon", UltimateRepairing.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "EXPERIENCE_BOTTLE" : "EXP_BOTTLE"),
o8("ITEM", "Interfaces.Item Icon", "DIAMOND"),
o9("Exit-Icon", "Interfaces.Exit Icon", UltimateRepairing.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "OAK_DOOR" : "WOOD_DOOR"),
o10("Buy-Icon", "Interfaces.Buy Icon", "EMERALD"),
o12("Glass-Type-1", "Interfaces.Glass Type 1", 7),
o13("Glass-Type-2", "Interfaces.Glass Type 2", 11),
o14("Glass-Type-3", "Interfaces.Glass Type 3", 3),
o15("Rainbow-Glass", "Interfaces.Replace Glass Type 1 With Rainbow Glass", false),
o16("Item-Match-Type", "Main.Repair Items Only With Items Of That Items Type", true),
o17("Enable-Default-Anvil-Function", "Main.Enable Default Anvil Function", true),
o18("Swap-Functions", "Main.Swap Right And Left Click Options", false),
o19("Perms-Only", "Main.Require Permission On UltimateRepairing Anvil Place", false),
o20("-", "Main.Particle Amount", 25),
o21("-", "Main.Particle Type", "SPELL_WITCH"),
DOWNLOAD_FILES("-", "System.Download Needed Data Files", true),
LANGUGE_MODE("-", "System.Language Mode", "en_US"),
o22("Debug-Mode", "System.Debugger Enabled", false);
private final String setting, oldSetting;
private final Object option;
private Setting(String oldSetting, String setting, Object option) {
this.oldSetting = oldSetting;
this.setting = setting;
this.option = option;
}
}
}

View File

@ -0,0 +1,21 @@
package com.songoda.ultimaterepairing.utils.settings;
public enum Category {
MAIN("General settings and options."),
INTERFACES("These settings allow you to alter the way interfaces look.",
"They are used in GUI's to make patterns, change them up then open up a",
"GUI to see how it works."),
SYSTEM("System related settings.");
private String[] comments;
Category(String... comments) {
this.comments = comments;
}
public String[] getComments() {
return comments;
}
}

View File

@ -0,0 +1,131 @@
package com.songoda.ultimaterepairing.utils.settings;
import com.songoda.ultimaterepairing.UltimateRepairing;
import com.songoda.ultimaterepairing.utils.ServerVersion;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public enum Setting {
TIMEOUT("Main.Time Before Repair Auto Canceled", 200L),
EXPERIENCE_EQUATION("Main.Experience Cost Equation", "{MaxDurability} - ({MaxDurability} - {Durability} / 40) + 1",
"The equation used to generate experience repairing cost."),
ECONOMY_EQUATION("Main.Economy Cost Equation", "{XPCost} * 5",
"The equation used to generate economy repairing cost."),
ITEM_EQUATION("Main.Item Cost Equation", "{XPCost} * 3",
"The equation used to generate item repairing cost."),
MULTIPLY_COST_FOR_ENCHANTED("Main.Cost Multiplier For Enchanted Items", 2,
"Should enchanted items have their repair costs multiplied?"),
VAULT_ECONOMY("Economy.Use Vault Economy", true,
"Should Vault be used?"),
RESERVE_ECONOMY("Economy.Use Reserve Economy", true,
"Should Reserve be used?"),
PLAYER_POINTS_ECONOMY("Economy.Use Player Points Economy", false,
"Should PlayerPoints be used?"),
ECO_ICON("Interfaces.Economy Icon", UltimateRepairing.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "SUNFLOWER" : "DOUBLE_PLANT"),
XP_ICON("Interfaces.XP Icon", UltimateRepairing.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "EXPERIENCE_BOTTLE" : "EXP_BOTTLE"),
ITEM_ICON("Interfaces.Item Icon", "DIAMOND"),
EXIT_ICON("Interfaces.Exit Icon", UltimateRepairing.getInstance().isServerVersionAtLeast(ServerVersion.V1_13) ? "OAK_DOOR" : "WOOD_DOOR"),
BUY_ICON("Interfaces.Buy Icon", "EMERALD"),
GLASS_TYPE_1("Interfaces.Glass Type 1", 7),
GLASS_TYPE_2("Interfaces.Glass Type 2", 11),
GLASS_TYPE_3("Interfaces.Glass Type 3", 3),
RAINBOW("Interfaces.Replace Glass Type 1 With Rainbow Glass", false),
REPAIR_ONLY_SAME_TYPE("Main.Repair Items Only With Items Of That Items Type", true,
"Should repairing with items only utilize items of the same type?"),
ENABLE_ANVIL_DEFAULT_FUNCTION("Main.Enable Default Anvil Function", true,
"Should the default anvil function be disabled?"),
SWAP_LEFT_RIGHT("Main.Swap Right And Left Click Options", false,
"Should punching an anvil open up the anvil GUI and right clicking",
"open up the repair GUI?"),
PERMISSION_ANVIL_PLACE("Main.Require Permission On UltimateRepairing Anvil Place", false,
"Should players need admin permissions to place anvils?"),
PARTICLE_AMOUNT("Main.Particle Amount", 25),
PARTICLE_TYPE("Main.Particle Type", "SPELL_WITCH"),
LANGUGE_MODE("System.Language Mode", "en_US",
"The enabled language file.",
"More language files (if available) can be found in the plugins data folder.");
private String setting;
private Object option;
private String[] comments;
Setting(String setting, Object option, String... comments) {
this.setting = setting;
this.option = option;
this.comments = comments;
}
Setting(String setting, Object option) {
this.setting = setting;
this.option = option;
this.comments = null;
}
public static Setting getSetting(String setting) {
List<Setting> settings = Arrays.stream(values()).filter(setting1 -> setting1.setting.equals(setting)).collect(Collectors.toList());
if (settings.isEmpty()) return null;
return settings.get(0);
}
public String getSetting() {
return setting;
}
public Object getOption() {
return option;
}
public String[] getComments() {
return comments;
}
public List<String> getStringList() {
return UltimateRepairing.getInstance().getConfig().getStringList(setting);
}
public boolean getBoolean() {
return UltimateRepairing.getInstance().getConfig().getBoolean(setting);
}
public int getInt() {
return UltimateRepairing.getInstance().getConfig().getInt(setting);
}
public long getLong() {
return UltimateRepairing.getInstance().getConfig().getLong(setting);
}
public String getString() {
return UltimateRepairing.getInstance().getConfig().getString(setting);
}
public char getChar() {
return UltimateRepairing.getInstance().getConfig().getString(setting).charAt(0);
}
public double getDouble() {
return UltimateRepairing.getInstance().getConfig().getDouble(setting);
}
}

View File

@ -0,0 +1,309 @@
package com.songoda.ultimaterepairing.utils.settings;
import com.songoda.ultimaterepairing.UltimateRepairing;
import com.songoda.ultimaterepairing.utils.Methods;
import com.songoda.ultimaterepairing.utils.ServerVersion;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.io.*;
import java.util.*;
/**
* Created by songoda on 6/4/2017.
*/
public class SettingsManager implements Listener {
private final UltimateRepairing plugin;
private Map<Player, String> cat = new HashMap<>();
private Map<Player, String> current = new HashMap<>();
public SettingsManager(UltimateRepairing plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
ItemStack clickedItem = event.getCurrentItem();
if (event.getInventory() != event.getWhoClicked().getOpenInventory().getTopInventory()
|| clickedItem == null || !clickedItem.hasItemMeta()
|| !clickedItem.getItemMeta().hasDisplayName()) {
return;
}
if (event.getView().getTitle().equals(plugin.getName() + " Settings Manager")) {
event.setCancelled(true);
if (clickedItem.getType().name().contains("STAINED_GLASS")) return;
String type = ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName());
this.cat.put((Player) event.getWhoClicked(), type);
this.openEditor((Player) event.getWhoClicked());
} else if (event.getView().getTitle().equals(plugin.getName() + " Settings Editor")) {
event.setCancelled(true);
if (clickedItem.getType().name().contains("STAINED_GLASS")) return;
Player player = (Player) event.getWhoClicked();
String key = cat.get(player) + "." + ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName());
if (plugin.getConfig().get(key).getClass().getName().equals("java.lang.Boolean")) {
this.plugin.getConfig().set(key, !plugin.getConfig().getBoolean(key));
this.finishEditing(player);
} else {
this.editObject(player, key);
}
}
}
@EventHandler
public void onChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
if (!current.containsKey(player)) return;
String value = current.get(player);
FileConfiguration config = plugin.getConfig();
if (config.isLong(value)) {
config.set(value, Long.parseLong(event.getMessage()));
} else if (config.isInt(value)) {
config.set(value, Integer.parseInt(event.getMessage()));
} else if (config.isDouble(value)) {
config.set(value, Double.parseDouble(event.getMessage()));
} else if (config.isString(value)) {
config.set(value, event.getMessage());
}
Bukkit.getScheduler().scheduleSyncDelayedTask(UltimateRepairing.getInstance(), () ->
this.finishEditing(player), 0L);
event.setCancelled(true);
}
private void finishEditing(Player player) {
this.current.remove(player);
this.saveConfig();
this.openEditor(player);
}
private void editObject(Player player, String current) {
this.current.put(player, ChatColor.stripColor(current));
player.closeInventory();
player.sendMessage("");
player.sendMessage(Methods.formatText("&7Please enter a value for &6" + current + "&7."));
if (plugin.getConfig().isInt(current) || plugin.getConfig().isDouble(current)) {
player.sendMessage(Methods.formatText("&cUse only numbers."));
}
player.sendMessage("");
}
public void openSettingsManager(Player player) {
Inventory inventory = Bukkit.createInventory(null, 27, plugin.getName() + " Settings Manager");
ItemStack glass = Methods.getGlass();
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, glass);
}
int slot = 10;
for (String key : plugin.getConfig().getDefaultSection().getKeys(false)) {
ItemStack item = new ItemStack(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.LEGACY_WOOL : Material.valueOf("WOOL"), 1, (byte) (slot - 9));
ItemMeta meta = item.getItemMeta();
meta.setLore(Collections.singletonList(Methods.formatText("&6Click To Edit This Category.")));
meta.setDisplayName(Methods.formatText("&f&l" + key));
item.setItemMeta(meta);
inventory.setItem(slot, item);
slot++;
}
player.openInventory(inventory);
}
private void openEditor(Player player) {
Inventory inventory = Bukkit.createInventory(null, 54, plugin.getName() + " Settings Editor");
FileConfiguration config = plugin.getConfig();
int slot = 0;
for (String key : config.getConfigurationSection(cat.get(player)).getKeys(true)) {
String fKey = cat.get(player) + "." + key;
ItemStack item = new ItemStack(Material.DIAMOND_HELMET);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(Methods.formatText("&6" + key));
List<String> lore = new ArrayList<>();
if (config.isBoolean(fKey)) {
item.setType(Material.LEVER);
lore.add(Methods.formatText(config.getBoolean(fKey) ? "&atrue" : "&cfalse"));
} else if (config.isString(fKey)) {
item.setType(Material.PAPER);
lore.add(Methods.formatText("&7" + config.getString(fKey)));
} else if (config.isInt(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getInt(fKey)));
} else if (config.isLong(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getLong(fKey)));
} else if (config.isDouble(fKey)) {
item.setType(plugin.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.CLOCK : Material.valueOf("WATCH"));
lore.add(Methods.formatText("&7" + config.getDouble(fKey)));
}
Setting setting = Setting.getSetting(fKey);
if (setting != null && setting.getComments() != null) {
lore.add("");
String comment = String.join(" ", setting.getComments());
int lastIndex = 0;
for (int n = 0; n < comment.length(); n++) {
if (n - lastIndex < 30)
continue;
if (comment.charAt(n) == ' ') {
lore.add(Methods.formatText("&8" + comment.substring(lastIndex, n).trim()));
lastIndex = n;
}
}
if (lastIndex - comment.length() < 30)
lore.add(Methods.formatText("&8" + comment.substring(lastIndex).trim()));
}
meta.setLore(lore);
item.setItemMeta(meta);
inventory.setItem(slot, item);
slot++;
}
player.openInventory(inventory);
}
public void reloadConfig() {
plugin.reloadConfig();
this.setupConfig();
}
public void setupConfig() {
FileConfiguration config = plugin.getConfig();
for (Setting setting : Setting.values()) {
config.addDefault(setting.getSetting(), setting.getOption());
}
plugin.getConfig().options().copyDefaults(true);
saveConfig();
}
private void saveConfig() {
String dump = plugin.getConfig().saveToString();
StringBuilder config = new StringBuilder();
BufferedReader bufReader = new BufferedReader(new StringReader(dump));
try {
boolean first = true;
String line;
int currentTab = 0;
String category = "";
while ((line = bufReader.readLine()) != null) {
if (line.trim().startsWith("#")) continue;
int tabChange = line.length() - line.trim().length();
if (currentTab != tabChange) {
category = category.contains(".") && tabChange != 0 ? category.substring(0, category.indexOf(".")) : "";
currentTab = tabChange;
}
if (line.endsWith(":")) {
bufReader.mark(1000);
String found = bufReader.readLine();
bufReader.reset();
if (!found.trim().startsWith("-")) {
String newCategory = line.substring(0, line.length() - 1).trim();
if (category.equals(""))
category = newCategory;
else
category += "." + newCategory;
currentTab = tabChange + 2;
if (!first) {
config.append("\n\n");
} else {
first = false;
}
if (!category.contains("."))
config.append("#").append("\n");
try {
Category categoryObj = Category.valueOf(category.toUpperCase()
.replace(" ", "_")
.replace(".", "_"));
config.append(new String(new char[tabChange]).replace('\0', ' '));
for (String l : categoryObj.getComments())
config.append("# ").append(l).append("\n");
} catch (IllegalArgumentException e) {
config.append("# ").append(category).append("\n");
}
if (!category.contains("."))
config.append("#").append("\n");
config.append(line).append("\n");
continue;
}
}
if (line.trim().startsWith("-")) {
config.append(line).append("\n");
continue;
}
String key = category + "." + (line.split(":")[0].trim());
for (Setting setting : Setting.values()) {
if (!setting.getSetting().equals(key) || setting.getComments() == null) continue;
config.append(" ").append("\n");
for (String l : setting.getComments()) {
config.append(new String(new char[currentTab]).replace('\0', ' '));
config.append("# ").append(l).append("\n");
}
}
config.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (!plugin.getDataFolder().exists())
plugin.getDataFolder().mkdir();
BufferedWriter writer =
new BufferedWriter(new FileWriter(new File(plugin.getDataFolder() + File.separator + "config.yml")));
writer.write(config.toString());
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}