- *
- * @param value
- * The value to set
- */
- protected void setData(Object value) {
- StackTraceElement st = new Exception().getStackTrace()[1];
- String mname = st.getMethodName();
- if (!mname.startsWith("set"))
- throw new UnsupportedOperationException("Can only use setData from a setXYZ method");
- getLoadedPlayers().get(uuid).data.put(mname.substring("set".length()).toLowerCase(), value);
- }
-
- /**
- *
- * Gets a player data entry for the caller plugin returning the desired type, which is an enum
- * It will automatically determine the key and the return type.
- * Usage:
- *
- *
- * @return The value or null if not found
- */
- protected > T getEnumData(Class cl) {
- StackTraceElement st = new Exception().getStackTrace()[1];
- String mname = st.getMethodName();
- if (!mname.startsWith("get"))
- throw new UnsupportedOperationException("Can only use getEnumData from a getXYZ method");
- final String retstr = (String) getLoadedPlayers().get(uuid).data
- .get(mname.substring("get".length()).toLowerCase());
- if (retstr != null)
- return Enum.valueOf(cl, retstr);
- else
- return null;
- }
-
- /**
- * Sets a player data entry based on the caller method
- * Usage:
- *
- *
- *
- *
- * @param value
- * The value to set
- */
- protected void setEnumData(Enum> value) {
- StackTraceElement st = new Exception().getStackTrace()[1];
- String mname = st.getMethodName();
- if (!mname.startsWith("set"))
- throw new UnsupportedOperationException("Can only use setEnumData from a setXYZ method");
- getLoadedPlayers().get(uuid).data.put(mname.substring("set".length()).toLowerCase(), value.toString());
- }
-
- /**
- *
- * Gets a player data entry for the caller plugin returning the desired type, which is a number
- * It will automatically determine the key and the return type.
- * Usage:
- *
- *
- *
- * {@code
- * public short getNumber() {
- * return getIntData();
- * }
- *
- *
- * @return The value or null if not found
- */
- @SuppressWarnings("unchecked")
- protected Optional getIntData(Class cl) {
- StackTraceElement st = new Exception().getStackTrace()[1];
- String mname = st.getMethodName();
- if (!mname.startsWith("get"))
- throw new UnsupportedOperationException("Can only use getIntData from a getXYZ method");
- Object obj = getLoadedPlayers().get(uuid).data.get(mname.substring("get".length()).toLowerCase());
- if (obj == null)
- return Optional.empty();
- if (obj instanceof Short)
- return Optional.of((T) obj);
- if (!(Integer.class.isAssignableFrom(obj.getClass())))
- throw new UnsupportedOperationException("The retrieved object isn't an integer: " + obj);
- Integer int_ = (Integer) obj;
- if (Short.class.isAssignableFrom(cl))
- return Optional.of((T) (Object) int_.shortValue());
- else
- return Optional.of((T) (Object) int_);
- }
-
- /**
- * Sets a player data entry based on the caller method
- * Usage:
- *
- *
- *
- *
- * @param value
- * The value to set
- */
- protected void setIntData(Number value) {
- StackTraceElement st = new Exception().getStackTrace()[1];
- String mname = st.getMethodName();
- if (!mname.startsWith("set"))
- throw new UnsupportedOperationException("Can only use setIntData from a setXYZ method");
- getLoadedPlayers().get(uuid).data.put(mname.substring("set".length()).toLowerCase(), value);
- }
-
- /**
- *
- * Gets a player data entry for the caller plugin returning a boolean.
- * Usage:
- *
- *
- * @return The value or false if not found
- */
- protected boolean getBoolData() {
- StackTraceElement st = new Exception().getStackTrace()[1];
- String mname = st.getMethodName();
- if (!mname.startsWith("get"))
- throw new UnsupportedOperationException("Can only use getData from a getXYZ method");
- Object ret = getLoadedPlayers().get(uuid).data.get(mname.substring("get".length()).toLowerCase());
- if (ret != null && !Boolean.class.isAssignableFrom(ret.getClass()))
- throw new UnsupportedOperationException("Not a boolean!");
- if (ret == null)
- return false;
- return (boolean) ret;
- }
-
- /**
- * Gets the player's Minecraft name
- *
- * @return The player's Minecraft name
- */
- public String getPlayerName() {
- return getData();
- }
-
- /**
- * Sets the player's Minecraft name
- *
- * @param playerName
- * the new name
- */
- public void setPlayerName(String playerName) {
- setData(playerName);
- }
-
- private UUID uuid; // Do not save it in the file
-
- /**
- * Get the player's UUID
- *
- * @return The Minecraft UUID of the player
- */
- public UUID getUuid() {
- return uuid;
- }
-
- private ConcurrentHashMap, TBMCPlayer> playermap = new ConcurrentHashMap<>(); // TODO
-
- /**
- * Gets the TBMCPlayer object as a specific plugin player, keeping it's data *
- *
- * @param p
- * Player to get
- * @param cl
- * The TBMCPlayer subclass
- */
- @SuppressWarnings("unchecked")
- public T asPluginPlayer(Class cl) {
- T obj = null;
- if (playermap.containsKey(cl))
- return (T) playermap.get(cl);
- try {
- obj = cl.newInstance();
- ((TBMCPlayer) obj).uuid = uuid;
- // ((TBMCPlayer) obj).data.putAll(data);
- playermap.put(cl, obj);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return obj;
- }
-
- private static HashMap LoadedPlayers = new HashMap<>();
-
- /**
- * This method returns a TBMC player from their name. Calling this method may return an offline player which will load it, therefore it's highly recommended to use {@link #close()} to unload the
- * player data. Using try-with-resources may be the easiest way to achieve this. Example:
- *
- *
- *
- * @param name
- * The player's name
- * @return The {@link TBMCPlayer} object for the player
- */
- public static TBMCPlayer getFromName(String name) {
- @SuppressWarnings("deprecation")
- OfflinePlayer p = Bukkit.getOfflinePlayer(name);
- if (p != null)
- return getPlayer(p);
- else
- return null;
- }
-
- /**
- * This method returns a TBMC player from a Bukkit player. Calling this method may return an offline player, therefore it's highly recommended to use {@link #close()} to unload the player data.
- * Using try-with-resources may be the easiest way to achieve this. Example:
- *
- *
- *
- * @param p
- * The Player object
- * @return The {@link TBMCPlayer} object for the player
- */
- public static TBMCPlayer getPlayer(OfflinePlayer p) {
- if (TBMCPlayer.getLoadedPlayers().containsKey(p.getUniqueId()))
- return TBMCPlayer.getLoadedPlayers().get(p.getUniqueId());
- else
- return TBMCPlayer.loadPlayer(p);
- }
-
- /**
- * This method returns a TBMC player from a player UUID. Calling this method may return an offline player, therefore it's highly recommended to use {@link #close()} to unload the player data.
- * Using try-with-resources may be the easiest way to achieve this. Example:
- *
- *
- *
- * @param p
- * The Player object
- * @return The {@link TBMCPlayer} object for the player
- */
- public static TBMCPlayer getPlayer(UUID uuid) {
- if (TBMCPlayer.getLoadedPlayers().containsKey(uuid))
- return TBMCPlayer.getLoadedPlayers().get(uuid);
- else
- return TBMCPlayer.loadPlayer(Bukkit.getOfflinePlayer(uuid));
- }
-
- /**
- * This is a convenience method for {@link #getPlayer(OfflinePlayer)}.{@link #asPluginPlayer(Class)}.
- *
- * See those methods for more information.
- *
- * @param p
- * Player to get
- * @param cl
- * The TBMCPlayer subclass
- * @return The player as a subtype of TBMCPlayer
- */
- public static T getPlayerAs(OfflinePlayer p, Class cl) {
- return getPlayer(p).asPluginPlayer(cl);
- }
-
- /**
- * This is a convenience method for {@link #getPlayer(UUID)}.{@link #asPluginPlayer(Class)}
- *
- * See those methods for more information.
- *
- * @param uuid
- * The UUID of the player to get
- * @param cl
- * The TBMCPlayer subclass
- * @return The player as a subtype of TBMCPlayer
- */
- public static T getPlayerAs(UUID uuid, Class cl) {
- return getPlayer(uuid).asPluginPlayer(cl);
- }
-
- /**
- * Only intended to use from ButtonCore
- */
- public static TBMCPlayer loadPlayer(OfflinePlayer p) {
- if (getLoadedPlayers().containsKey(p.getUniqueId()))
- return getLoadedPlayers().get(p.getUniqueId());
- File file = new File(TBMC_PLAYERS_DIR);
- file.mkdirs();
- file = new File(TBMC_PLAYERS_DIR, p.getUniqueId().toString() + ".yml");
- if (!file.exists())
- return addPlayer(p);
- else {
- final YamlConfiguration yc = new YamlConfiguration();
- try {
- yc.load(file);
- } catch (Exception e) {
- new Exception("Failed to load player data for " + p.getUniqueId(), e).printStackTrace();
- return null;
- }
- TBMCPlayer player = new TBMCPlayer();
- player.uuid = p.getUniqueId();
- player.data.putAll(yc.getValues(true));
- getLoadedPlayers().put(p.getUniqueId(), player); // Accessing any value requires it to be in the map
- Bukkit.getLogger().info("Loaded player: " + player.getPlayerName());
- if (player.getPlayerName() == null) {
- player.setPlayerName(p.getName());
- Bukkit.getLogger().info("Player name saved: " + player.getPlayerName());
- } else if (!p.getName().equals(player.getPlayerName())) {
- Bukkit.getLogger().info("Renaming " + player.getPlayerName() + " to " + p.getName());
- TownyUniverse tu = Towny.getPlugin(Towny.class).getTownyUniverse();
- Resident resident = tu.getResidentMap().get(player.getPlayerName());
- if (resident == null)
- Bukkit.getLogger().warning("Resident not found - couldn't rename in Towny.");
- else if (tu.getResidentMap().contains(p.getName()))
- Bukkit.getLogger().warning("Target resident name is already in use."); // TODO: Handle
- else
- resident.setName(p.getName());
- player.setPlayerName(p.getName());
- Bukkit.getLogger().info("Renaming done.");
- }
-
- // Load in other plugins
- Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerLoadEvent(yc, player));
- return player;
- }
- }
-
- /**
- * Only intended to use from ButtonCore
- */
- public static TBMCPlayer addPlayer(OfflinePlayer p) {
- TBMCPlayer player = new TBMCPlayer();
- player.uuid = p.getUniqueId();
- getLoadedPlayers().put(p.getUniqueId(), player); // Accessing any value requires it to be in the map
- player.setPlayerName(p.getName());
- Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerAddEvent(player));
- savePlayer(player);
- return player;
- }
-
- /**
- * Only intended to use from ButtonCore
- */
- public static void savePlayer(TBMCPlayer player) {
- YamlConfiguration yc = new YamlConfiguration();
- for (Entry item : player.data.entrySet())
- yc.set(item.getKey(), item.getValue());
- Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerSaveEvent(yc, player));
- try {
- yc.save(TBMC_PLAYERS_DIR + "/" + player.uuid + ".yml");
- } catch (IOException e) {
- new Exception("Failed to save player data for " + player.getPlayerName(), e).printStackTrace();
- }
- }
-
- /**
- * Only intended to use from ButtonCore
- */
- public static void joinPlayer(TBMCPlayer player) {
- getLoadedPlayers().put(player.uuid, player);
- Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerJoinEvent(player));
- }
-
- /**
- * Only intended to use from ButtonCore
- */
- public static void quitPlayer(TBMCPlayer player) {
- Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerQuitEvent(player));
- getLoadedPlayers().remove(player.uuid);
- }
-
- /**
- * By default the player data will only get cleaned from memory when the player quits. Therefore this method must be called when accessing an offline player to clean the player data up. Calling
- * this method will have no effect on online players.
- * Therefore, the recommended use is to call it when using {@link #GetPlayer} or use try-with-resources.
- */
- @Override
- public void close() {
- final Player player = Bukkit.getPlayer(uuid);
- if (player == null || !player.isOnline())
- getLoadedPlayers().remove(uuid);
- }
-
- public static HashMap getLoadedPlayers() {
- return LoadedPlayers;
- }
-
- /**
- * Get player information. This method calls the {@link TBMCPlayerGetInfoEvent} to get all the player information across the TBMC plugins.
- *
- * @param target
- * The {@link InfoTarget} to return the info for.
- * @return The player information.
- */
- public String getInfo(InfoTarget target) {
- TBMCPlayerGetInfoEvent event = new TBMCPlayerGetInfoEvent(this, target);
- Bukkit.getServer().getPluginManager().callEvent(event);
- return event.getResult();
- }
-
- public enum InfoTarget {
- MCHover, MCCommand, Discord
- }
-}
diff --git a/src/main/java/buttondevteam/lib/TBMCPlayerAddEvent.java b/src/main/java/buttondevteam/lib/TBMCPlayerAddEvent.java
deleted file mode 100644
index 46ccb4f..0000000
--- a/src/main/java/buttondevteam/lib/TBMCPlayerAddEvent.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package buttondevteam.lib;
-
-import org.bukkit.event.Event;
-import org.bukkit.event.HandlerList;
-
-/**
- *
- * This event gets called when a new player joins. After this event, the
- * {@link TBMCPlayerSaveEvent} will be called.
- *
- *
- * @author Norbi
- *
- */
-public class TBMCPlayerAddEvent extends Event {
- private static final HandlerList handlers = new HandlerList();
-
- private TBMCPlayer player;
-
- public TBMCPlayerAddEvent(TBMCPlayer player) {
- this.player = player;
- }
-
- public TBMCPlayer GetPlayer() {
- return player;
- }
-
- @Override
- public HandlerList getHandlers() {
- return handlers;
- }
-
- public static HandlerList getHandlerList() {
- return handlers;
- }
-}
\ No newline at end of file
diff --git a/src/main/java/buttondevteam/lib/TBMCPlayerBase.java b/src/main/java/buttondevteam/lib/TBMCPlayerBase.java
deleted file mode 100644
index cac3068..0000000
--- a/src/main/java/buttondevteam/lib/TBMCPlayerBase.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package buttondevteam.lib;
-
-public abstract class TBMCPlayerBase {
- /**
- * This method returns the filename for this player data. For example, for Minecraft-related data, use MC UUIDs, for Discord data, use Discord IDs, etc.
- */
- public abstract String getFileName();
-
- /**
- * This method returns the folder the file is in. For example, for Minecraft data, this should be "minecraft", for Discord, "discord", etc.
- */
- public abstract String getFolder();
-
-
-}
diff --git a/src/main/java/buttondevteam/lib/player/AbstractUserClass.java b/src/main/java/buttondevteam/lib/player/AbstractUserClass.java
new file mode 100644
index 0000000..f6554e1
--- /dev/null
+++ b/src/main/java/buttondevteam/lib/player/AbstractUserClass.java
@@ -0,0 +1,28 @@
+package buttondevteam.lib.player;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Specifies a {@link ChromaGamerBase} direct subclass which's abstract. For Minecraft data, use {@link PlayerClass}
+ *
+ * @author NorbiPeti
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+@Inherited
+public @interface AbstractUserClass {
+ /**
+ * Indicates which folder should the player files be saved in.
+ */
+ String foldername();
+
+ /**
+ * Indicates the class to create when connecting accounts.
+ */
+ Class> prototype();
+}
diff --git a/src/main/java/buttondevteam/lib/player/ChromaGamerBase.java b/src/main/java/buttondevteam/lib/player/ChromaGamerBase.java
new file mode 100644
index 0000000..944b676
--- /dev/null
+++ b/src/main/java/buttondevteam/lib/player/ChromaGamerBase.java
@@ -0,0 +1,262 @@
+package buttondevteam.lib.player;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map.Entry;
+import java.util.function.Consumer;
+
+import org.bukkit.Bukkit;
+import org.bukkit.configuration.file.YamlConfiguration;
+import buttondevteam.lib.TBMCCoreAPI;
+
+public abstract class ChromaGamerBase implements AutoCloseable {
+ public static final String TBMC_PLAYERS_DIR = "TBMC/players/";
+
+ private static final HashMap, String> playerTypes = new HashMap<>();
+
+ /**
+ * Used for connecting with every type of user ({@link #connectWith(ChromaGamerBase)})
+ */
+ public static void RegisterPluginUserClass(Class extends ChromaGamerBase> userclass) {
+ if (userclass.isAnnotationPresent(UserClass.class))
+ playerTypes.put(userclass, userclass.getAnnotation(UserClass.class).foldername());
+ else if (userclass.isAnnotationPresent(AbstractUserClass.class))
+ playerTypes.put(userclass.getAnnotation(AbstractUserClass.class).prototype(),
+ userclass.getAnnotation(AbstractUserClass.class).foldername());
+ else // <-- Really important
+ throw new RuntimeException("Class not registered as a user class! Use @UserClass or TBMCPlayerBase");
+ }
+
+ /**
+ * Returns the folder name for the given player class.
+ *
+ * @param cl
+ * The class to get the folder from (like {@link TBMCPlayerBase} or one of it's subclasses
+ * @return The folder name for the given type
+ * @throws RuntimeException
+ * If the class doesn't have the {@link UserClass} annotation.
+ */
+ public static String getFolderForType(Class cl) {
+ if (cl.isAnnotationPresent(UserClass.class))
+ return cl.getAnnotation(UserClass.class).foldername();
+ else if (cl.isAnnotationPresent(AbstractUserClass.class))
+ return cl.getAnnotation(AbstractUserClass.class).foldername();
+ throw new RuntimeException("Class not registered as a user class! Use @UserClass or @AbstractUserClass");
+ }
+
+ /**
+ * This method returns the filename for this player data. For example, for Minecraft-related data, MC UUIDs, for Discord data, use Discord IDs, etc.
+ * Does not include .yml
+ */
+ public final String getFileName() {
+ return plugindata.getString(getFolder() + "_id");
+ }
+
+ /**
+ * Use {@link #data()} or {@link #data(String)} where possible; the 'id' must be always set
+ */
+ protected YamlConfiguration plugindata;
+
+ /***
+ * Loads a user from disk and returns the user object. Make sure to use the subclasses' methods, where possible, like {@link TBMCPlayerBase#getPlayer(java.util.UUID, Class)}
+ *
+ * @param fname
+ * @param cl
+ * @return
+ */
+ public static T getUser(String fname, Class cl) {
+ try {
+ T obj = cl.newInstance();
+ final String folder = getFolderForType(cl);
+ final File file = new File(TBMC_PLAYERS_DIR + folder, fname + ".yml");
+ file.getParentFile().mkdirs();
+ obj.plugindata = YamlConfiguration.loadConfiguration(file);
+ obj.plugindata.set(folder + "_id", fname);
+ return obj;
+ } catch (Exception e) {
+ TBMCCoreAPI.SendException("An error occured while loading a " + cl.getSimpleName() + "!", e);
+ }
+ return null;
+ }
+
+ /**
+ * Saves the player. It'll pass all exceptions to the caller. To automatically handle the exception, use {@link #save()} instead.
+ */
+ @Override
+ public void close() throws Exception {
+ if (plugindata.getKeys(false).size() > 0)
+ plugindata.save(new File(TBMC_PLAYERS_DIR + getFolder(), getFileName() + ".yml"));
+ }
+
+ /**
+ * Saves the player. It'll handle all exceptions that may happen. To catch the exception, use {@link #close()} instead.
+ */
+ public void save() {
+ try {
+ close();
+ } catch (Exception e) {
+ TBMCCoreAPI.SendException("Error while saving player to " + getFolder() + "/" + getFileName() + ".yml!", e);
+ }
+ }
+
+ /**
+ * Connect two accounts. Do not use for connecting two Minecraft accounts or similar. Also make sure you have the "id" tag set
+ *
+ * @param user
+ * The account to connect with
+ */
+ public void connectWith(T user) {
+ // Set the ID, go through all linked files and connect them as well
+ if (!playerTypes.containsKey(getClass()))
+ throw new RuntimeException("Class not registered as a user class! Use TBMCCoreAPI.RegisterUserClass");
+ final String ownFolder = getFolder();
+ user.plugindata.set(ownFolder + "_id", plugindata.getString(ownFolder + "_id"));
+ final String userFolder = user.getFolder();
+ plugindata.set(userFolder + "_id", user.plugindata.getString(userFolder + "_id"));
+ Consumer sync = sourcedata -> {
+ final String sourcefolder = sourcedata == plugindata ? ownFolder : userFolder;
+ final String id = sourcedata.getString(sourcefolder + "_id");
+ for (Entry, String> entry : playerTypes.entrySet()) { // Set our ID in all files we can find, both from our connections and the new ones
+ if (entry.getKey() == getClass() || entry.getKey() == user.getClass())
+ continue;
+ final String otherid = sourcedata.getString(entry.getValue() + "_id");
+ if (otherid == null)
+ continue;
+ try (@SuppressWarnings("unchecked")
+ ChromaGamerBase cg = getUser(otherid, (Class) entry.getKey())) {
+ cg.plugindata.set(sourcefolder + "_id", id); // Set new IDs
+ for (Entry, String> item : playerTypes.entrySet())
+ if (sourcedata.contains(item.getValue() + "_id"))
+ cg.plugindata.set(item.getValue() + "_id", sourcedata.getString(item.getValue() + "_id")); // Set all existing IDs
+ } catch (Exception e) {
+ TBMCCoreAPI.SendException("Failed to update " + sourcefolder + " ID in player files for " + id
+ + " in folder with " + entry.getValue() + " id " + otherid + "!", e);
+ }
+ }
+ };
+ sync.accept(plugindata);
+ sync.accept(user.plugindata);
+ }
+
+ /**
+ * Retunrs the ID for the T typed player object connected with this one or null if no connection found.
+ *
+ * @param cl
+ * The player class to get the ID from
+ * @return The ID or null if not found
+ */
+ public String getConnectedID(Class cl) {
+ return plugindata.getString(getFolderForType(cl) + "_id");
+ }
+
+ /**
+ * Returns this player as a plugin player. This will return a new instance unless the player is online.
+ * Make sure to close both the returned and this object. A try-with-resources block or two can help.
+ *
+ * @param cl
+ * The target player class
+ * @return The player as a {@link T} object or null if not having an account there
+ */
+ @SuppressWarnings("unchecked")
+ public T getAs(Class cl) { // TODO: Provide a way to use TBMCPlayerBase's loaded players
+ if (cl.getSimpleName().equals(getClass().getSimpleName()))
+ return (T) this;
+ String newfolder = getFolderForType(cl);
+ if (newfolder == null)
+ throw new RuntimeException("The specified class " + cl.getSimpleName() + " isn't registered!");
+ if (newfolder.equals(getFolder())) // If in the same folder, the same filename is used
+ return getUser(getFileName(), cl);
+ if (!plugindata.contains(newfolder + "_id"))
+ return null;
+ return getUser(plugindata.getString(newfolder + "_id"), cl);
+ }
+
+ public String getFolder() {
+ return getFolderForType(getClass());
+ }
+
+ private void ThrowIfNoUser() {
+ if (!getClass().isAnnotationPresent(UserClass.class)
+ && !getClass().isAnnotationPresent(AbstractUserClass.class))
+ throw new RuntimeException("Class not registered as a user class! Use @UserClass");
+ }
+
+ @SuppressWarnings("rawtypes")
+ private HashMap datamap = new HashMap<>();
+
+ /**
+ * Use from a data() method, which is in a method with the name of the key. For example, use flair() for the enclosing method of the outer data() to save to and load from "flair"
+ *
+ * @return A data object with methods to get and set
+ */
+ @SuppressWarnings("unchecked")
+ protected PlayerData data(String sectionname) {
+ ThrowIfNoUser();
+ String mname = sectionname + "." + new Exception().getStackTrace()[2].getMethodName();
+ if (!datamap.containsKey(mname))
+ datamap.put(mname, new PlayerData(mname, plugindata));
+ return datamap.get(mname);
+ }
+
+ /**
+ * Use from a method with the name of the key. For example, use flair() for the enclosing method to save to and load from "flair"
+ *
+ * @return A data object with methods to get and set
+ */
+ @SuppressWarnings("unchecked")
+ protected PlayerData data() {
+ ThrowIfNoUser();
+ String mname = new Exception().getStackTrace()[1].getMethodName();
+ if (!datamap.containsKey(mname))
+ datamap.put(mname, new PlayerData(mname, plugindata));
+ return datamap.get(mname);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private HashMap dataenummap = new HashMap<>();
+
+ /**
+ * Use from a data() method, which is in a method with the name of the key. For example, use flair() for the enclosing method of the outer data() to save to and load from "flair"
+ *
+ * @return A data object with methods to get and set
+ */
+ @SuppressWarnings("unchecked")
+ protected > EnumPlayerData dataEnum(String sectionname, Class cl) {
+ ThrowIfNoUser();
+ String mname = sectionname + "." + new Exception().getStackTrace()[2].getMethodName();
+ if (!dataenummap.containsKey(mname))
+ dataenummap.put(mname, new EnumPlayerData(mname, plugindata, cl));
+ return dataenummap.get(mname);
+ }
+
+ /**
+ * Use from a method with the name of the key. For example, use flair() for the enclosing method to save to and load from "flair"
+ *
+ * @return A data object with methods to get and set
+ */
+ @SuppressWarnings("unchecked")
+ protected > EnumPlayerData dataEnum(Class cl) {
+ ThrowIfNoUser();
+ String mname = new Exception().getStackTrace()[1].getMethodName();
+ if (!dataenummap.containsKey(mname))
+ dataenummap.put(mname, new EnumPlayerData(mname, plugindata, cl));
+ return dataenummap.get(mname);
+ }
+
+ /**
+ * Get player information. This method calls the {@link TBMCPlayerGetInfoEvent} to get all the player information across the TBMC plugins.
+ *
+ * @param target
+ * The {@link InfoTarget} to return the info for.
+ * @return The player information.
+ */
+ public String getInfo(InfoTarget target) {
+ TBMCPlayerGetInfoEvent event = new TBMCPlayerGetInfoEvent(this, target);
+ Bukkit.getServer().getPluginManager().callEvent(event);
+ return event.getResult();
+ }
+
+ public enum InfoTarget {
+ MCHover, MCCommand, Discord
+ }
+}
diff --git a/src/main/java/buttondevteam/lib/player/EnumPlayerData.java b/src/main/java/buttondevteam/lib/player/EnumPlayerData.java
new file mode 100644
index 0000000..fcc31af
--- /dev/null
+++ b/src/main/java/buttondevteam/lib/player/EnumPlayerData.java
@@ -0,0 +1,29 @@
+package buttondevteam.lib.player;
+
+import org.bukkit.configuration.file.YamlConfiguration;
+
+public class EnumPlayerData> {
+ private PlayerData data;
+ private Class cl;
+
+ public EnumPlayerData(String name, YamlConfiguration yaml, Class cl) {
+ data = new PlayerData(name, yaml);
+ this.cl = cl;
+ }
+
+ public T get() {
+ String str = data.get();
+ if (str == null || str.equals(""))
+ return null;
+ return Enum.valueOf(cl, str);
+ }
+
+ public void set(T value) {
+ data.set(value.toString());
+ }
+
+ public T getOrDefault(T def) {
+ T value = get();
+ return value == null ? def : value;
+ }
+}
diff --git a/src/main/java/buttondevteam/lib/player/PlayerClass.java b/src/main/java/buttondevteam/lib/player/PlayerClass.java
new file mode 100644
index 0000000..4c22784
--- /dev/null
+++ b/src/main/java/buttondevteam/lib/player/PlayerClass.java
@@ -0,0 +1,21 @@
+package buttondevteam.lib.player;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Specifies a {@link TBMCPlayerBase} direct subclass. For Minecraft data, use {@link UserClass}
+ *
+ * @author NorbiPeti
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface PlayerClass {
+ /**
+ * Indicates the plugin's name which this player class belongs to. Used to create a section for each plugin.
+ */
+ String pluginname();
+}
diff --git a/src/main/java/buttondevteam/lib/player/PlayerData.java b/src/main/java/buttondevteam/lib/player/PlayerData.java
new file mode 100644
index 0000000..05d68ca
--- /dev/null
+++ b/src/main/java/buttondevteam/lib/player/PlayerData.java
@@ -0,0 +1,33 @@
+package buttondevteam.lib.player;
+
+import org.bukkit.configuration.file.YamlConfiguration;
+
+public class PlayerData {
+ private String name;
+ private YamlConfiguration yaml;
+
+ public PlayerData(String name, YamlConfiguration yaml) {
+ this.name = name;
+ this.yaml = yaml;
+ }
+
+ @SuppressWarnings("unchecked")
+ public T get() {
+ Object value = yaml.get(name);
+ return (T) value;
+ }
+
+ public void set(T value) {
+ yaml.set(name, value);
+ }
+
+ public T getOrDefault(T def) {
+ T value = get();
+ return value == null ? def : value;
+ }
+
+ @Override
+ public String toString() {
+ return get().toString();
+ }
+}
diff --git a/src/main/java/buttondevteam/lib/player/TBMCPlayer.java b/src/main/java/buttondevteam/lib/player/TBMCPlayer.java
new file mode 100644
index 0000000..617af5e
--- /dev/null
+++ b/src/main/java/buttondevteam/lib/player/TBMCPlayer.java
@@ -0,0 +1,6 @@
+package buttondevteam.lib.player;
+
+@PlayerClass(pluginname = "ButtonCore")
+public final class TBMCPlayer extends TBMCPlayerBase {
+
+}
diff --git a/src/main/java/buttondevteam/lib/player/TBMCPlayerBase.java b/src/main/java/buttondevteam/lib/player/TBMCPlayerBase.java
new file mode 100644
index 0000000..e4f38c2
--- /dev/null
+++ b/src/main/java/buttondevteam/lib/player/TBMCPlayerBase.java
@@ -0,0 +1,220 @@
+package buttondevteam.lib.player;
+
+import java.util.Iterator;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.bukkit.Bukkit;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.entity.Player;
+
+import com.palmergames.bukkit.towny.Towny;
+import com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException;
+import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
+import com.palmergames.bukkit.towny.object.Resident;
+import com.palmergames.bukkit.towny.object.TownyUniverse;
+
+import buttondevteam.lib.TBMCCoreAPI;
+
+@AbstractUserClass(foldername = "minecraft", prototype = TBMCPlayer.class)
+public abstract class TBMCPlayerBase extends ChromaGamerBase {
+ protected UUID uuid;
+
+ private String pluginname;
+
+ protected TBMCPlayerBase() {
+ if (getClass().isAnnotationPresent(PlayerClass.class))
+ pluginname = getClass().getAnnotation(PlayerClass.class).pluginname();
+ else
+ throw new RuntimeException("Class not defined as player class! Use @PlayerClass");
+ }
+
+ public UUID getUUID() {
+ if (uuid == null)
+ uuid = UUID.fromString(getFileName());
+ return uuid;
+ }
+
+ public PlayerData PlayerName() {
+ return super.data();
+ }
+
+ /**
+ * Use from a method with the name of the key. For example, use flair() for the enclosing method to save to and load from "flair"
+ *
+ * @return A data object with methods to get and set
+ */
+ @Override
+ protected PlayerData data() {
+ return super.data(pluginname);
+ }
+
+ /**
+ * Use from a method with the name of the key. For example, use flair() for the enclosing method to save to and load from "flair"
+ *
+ * @return A data object with methods to get and set
+ */
+ @Override
+ protected > EnumPlayerData dataEnum(Class cl) {
+ return super.dataEnum(pluginname, cl);
+ }
+
+ /**
+ * Get player as a plugin player
+ *
+ * @param uuid
+ * The UUID of the player to get
+ * @param cl
+ * The type of the player
+ * @return The requested player object
+ */
+ @SuppressWarnings("unchecked")
+ public static T getPlayer(UUID uuid, Class cl) {
+ if (playermap.containsKey(uuid + "-" + cl.getSimpleName()))
+ return (T) playermap.get(uuid + "-" + cl.getSimpleName());
+ // System.out.println("A");
+ try {
+ T player;
+ if (playermap.containsKey(uuid + "-" + TBMCPlayer.class.getSimpleName())) {
+ // System.out.println("B"); - Don't program when tired
+ player = cl.newInstance();
+ player.plugindata = playermap.get(uuid + "-" + TBMCPlayer.class.getSimpleName()).plugindata;
+ playermap.put(uuid + "-" + cl.getSimpleName(), player); // It will get removed on player quit
+ } else
+ player = ChromaGamerBase.getUser(uuid.toString(), cl);
+ // System.out.println("C");
+ player.uuid = uuid;
+ return player;
+ } catch (Exception e) {
+ TBMCCoreAPI.SendException(
+ "Failed to get player with UUID " + uuid + " and class " + cl.getSimpleName() + "!", e);
+ return null;
+ }
+ }
+
+ /**
+ * Key: UUID-Class
+ */
+ static final ConcurrentHashMap playermap = new ConcurrentHashMap<>();
+
+ /**
+ * Gets the TBMCPlayer object as a specific plugin player, keeping it's data
+ * Make sure to use try-with-resources with this to save the data, as it may need to load the file
+ *
+ * @param cl
+ * The TBMCPlayer subclass
+ */
+ public T asPluginPlayer(Class cl) {
+ return getPlayer(uuid, cl);
+ }
+
+ /**
+ * Only intended to use from ButtonCore
+ */
+ public static void savePlayer(TBMCPlayerBase player) {
+ Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerSaveEvent(player));
+ try {
+ player.close();
+ } catch (Exception e) {
+ new Exception("Failed to save player data for " + player.PlayerName().get(), e).printStackTrace();
+ }
+ }
+
+ /**
+ * Only intended to use from ButtonCore
+ */
+ public static void joinPlayer(Player p) {
+ TBMCPlayer player = TBMCPlayerBase.getPlayer(p.getUniqueId(), TBMCPlayer.class);
+ Bukkit.getLogger().info("Loaded player: " + player.PlayerName().get());
+ if (player.PlayerName().get() == null) {
+ player.PlayerName().set(p.getName());
+ Bukkit.getLogger().info("Player name saved: " + player.PlayerName().get());
+ } else if (!p.getName().equals(player.PlayerName().get())) {
+ Bukkit.getLogger().info("Renaming " + player.PlayerName().get() + " to " + p.getName());
+ TownyUniverse tu = Towny.getPlugin(Towny.class).getTownyUniverse();
+ Resident resident = tu.getResidentMap().get(player.PlayerName().get());
+ if (resident == null) {
+ Bukkit.getLogger().warning("Resident not found - couldn't rename in Towny.");
+ TBMCCoreAPI.sendDebugMessage("Resident not found - couldn't rename in Towny.");
+ } else if (tu.getResidentMap().contains(p.getName())) {
+ Bukkit.getLogger().warning("Target resident name is already in use."); // TODO: Handle
+ TBMCCoreAPI.sendDebugMessage("Target resident name is already in use.");
+ } else
+ try {
+ TownyUniverse.getDataSource().renamePlayer(resident, p.getName());
+ } catch (AlreadyRegisteredException e) {
+ TBMCCoreAPI.SendException("Failed to rename resident, there's already one with this name.", e);
+ } catch (NotRegisteredException e) {
+ TBMCCoreAPI.SendException("Failed to rename resident, the resident isn't registered.", e);
+ }
+ player.PlayerName().set(p.getName());
+ Bukkit.getLogger().info("Renaming done.");
+ }
+ playermap.put(p.getUniqueId() + "-" + TBMCPlayer.class.getSimpleName(), player);
+
+ // Load in other plugins
+ Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerLoadEvent(player));
+ Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerJoinEvent(player));
+ player.save();
+ }
+
+ /**
+ * Only intended to use from ButtonCore
+ */
+ public static void quitPlayer(Player p) {
+ final TBMCPlayerBase player = playermap.get(p.getUniqueId() + "-" + TBMCPlayer.class.getSimpleName());
+ player.save();
+ Bukkit.getServer().getPluginManager().callEvent(new TBMCPlayerQuitEvent(player));
+ Iterator> it = playermap.entrySet().iterator();
+ while (it.hasNext()) {
+ Entry entry = it.next();
+ if (entry.getKey().startsWith(p.getUniqueId().toString()))
+ it.remove();
+ }
+ }
+
+ public static void savePlayers() {
+ playermap.values().stream().forEach(p -> {
+ try {
+ p.close();
+ } catch (Exception e) {
+ TBMCCoreAPI.SendException("Error while saving player " + p.PlayerName().get() + " (" + p.getFolder()
+ + "/" + p.getFileName() + ")!", e);
+ }
+ });
+ }
+
+ /**
+ * This method returns a TBMC player from their name. Calling this method may return an offline player which will load it, therefore it's highly recommended to use {@link #close()} to unload the
+ * player data. Using try-with-resources may be the easiest way to achieve this. Example:
+ *
+ *