forked from Fascinated/Bat
big ass refactor to handle loading guilds and users without spring to make it more futureproof
This commit is contained in:
@ -1,6 +1,9 @@
|
||||
package cc.fascinated.bat.common;
|
||||
|
||||
import cc.fascinated.bat.BatApplication;
|
||||
import lombok.Getter;
|
||||
import lombok.SneakyThrows;
|
||||
import org.bson.Document;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@ -9,11 +12,11 @@ import java.util.Map;
|
||||
* @author Fascinated (fascinated7)
|
||||
*/
|
||||
@Getter
|
||||
public class ProfileHolder {
|
||||
public abstract class ProfileHolder {
|
||||
/**
|
||||
* The profiles for the holder
|
||||
*/
|
||||
private Map<String, Profile> profiles;
|
||||
private final Map<String, Serializable> profiles = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Gets a profile for the holder
|
||||
@ -22,19 +25,25 @@ public class ProfileHolder {
|
||||
* @param <T> The type of the profile
|
||||
* @return The profile
|
||||
*/
|
||||
public <T extends Profile> T getProfile(Class<T> clazz) {
|
||||
if (profiles == null) {
|
||||
profiles = new HashMap<>();
|
||||
}
|
||||
public abstract <T extends Serializable> T getProfile(Class<T> clazz);
|
||||
|
||||
Profile profile = profiles.values().stream().filter(clazz::isInstance).findFirst().orElse(null);
|
||||
/**
|
||||
* Gets the profiles for the holder
|
||||
* using the provided document
|
||||
*
|
||||
* @return the profiles
|
||||
*/
|
||||
@SneakyThrows
|
||||
protected <T extends Serializable> T getProfileFromDocument(Class<T> clazz, Document document) {
|
||||
Serializable profile = getProfiles().get(clazz.getSimpleName());
|
||||
if (profile == null) {
|
||||
try {
|
||||
profile = clazz.newInstance();
|
||||
profiles.put(profile.getProfileKey(), profile);
|
||||
} catch (InstantiationException | IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
T newProfile = clazz.cast(clazz.getDeclaredConstructors()[0].newInstance());
|
||||
org.bson.Document profiles = document.get("profiles", new org.bson.Document());
|
||||
org.bson.Document profileDocument = (org.bson.Document) profiles.getOrDefault(clazz.getSimpleName(), new org.bson.Document());
|
||||
|
||||
newProfile.load(profileDocument, BatApplication.GSON);
|
||||
getProfiles().put(clazz.getSimpleName(), newProfile);
|
||||
return newProfile;
|
||||
}
|
||||
return clazz.cast(profile);
|
||||
}
|
||||
|
Reference in New Issue
Block a user