Bat/src/main/java/cc/fascinated/bat/common/ProfileHolder.java

51 lines
1.5 KiB
Java
Raw Normal View History

2024-06-25 12:36:40 +01:00
package cc.fascinated.bat.common;
import cc.fascinated.bat.BatApplication;
2024-06-25 12:36:40 +01:00
import lombok.Getter;
import lombok.SneakyThrows;
import org.bson.Document;
2024-06-25 12:36:40 +01:00
import java.util.HashMap;
import java.util.Map;
/**
* @author Fascinated (fascinated7)
*/
@Getter
public abstract class ProfileHolder {
2024-06-25 12:36:40 +01:00
/**
* The profiles for the holder
*/
private final Map<String, Serializable> profiles = new HashMap<>();
2024-06-25 12:36:40 +01:00
/**
* Gets a profile for the holder
*
* @param clazz The class of the profile
2024-06-28 03:01:21 +01:00
* @param <T> The type of the profile
2024-06-25 12:36:40 +01:00
* @return The profile
*/
public abstract <T extends Serializable> T getProfile(Class<T> clazz);
2024-06-25 12:36:40 +01:00
/**
* 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());
2024-06-25 12:36:40 +01:00
if (profile == null) {
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;
2024-06-25 12:36:40 +01:00
}
return clazz.cast(profile);
2024-06-25 12:36:40 +01:00
}
}