2024-06-25 12:36:40 +01:00
|
|
|
package cc.fascinated.bat.common;
|
|
|
|
|
2024-07-01 01:12:32 +01:00
|
|
|
import cc.fascinated.bat.BatApplication;
|
2024-06-25 12:36:40 +01:00
|
|
|
import lombok.Getter;
|
2024-07-01 01:12:32 +01:00
|
|
|
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
|
2024-07-01 01:12:32 +01:00
|
|
|
public abstract class ProfileHolder {
|
2024-06-25 12:36:40 +01:00
|
|
|
/**
|
|
|
|
* The profiles for the holder
|
|
|
|
*/
|
2024-07-01 01:12:32 +01:00
|
|
|
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
|
|
|
|
*/
|
2024-07-01 01:12:32 +01:00
|
|
|
public abstract <T extends Serializable> T getProfile(Class<T> clazz);
|
2024-06-25 12:36:40 +01:00
|
|
|
|
2024-07-01 01:12:32 +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) {
|
2024-07-01 01:12:32 +01:00
|
|
|
T newProfile = clazz.cast(clazz.getDeclaredConstructors()[0].newInstance());
|
2024-07-01 19:40:32 +01:00
|
|
|
Document profiles = document.get("profiles", new org.bson.Document());
|
|
|
|
Document profileDocument = (Document) profiles.get(clazz.getSimpleName());
|
2024-07-01 01:12:32 +01:00
|
|
|
|
2024-07-01 19:40:32 +01:00
|
|
|
newProfile.load(profileDocument == null ? new Document() : profileDocument, BatApplication.GSON);
|
2024-07-01 01:12:32 +01:00
|
|
|
getProfiles().put(clazz.getSimpleName(), newProfile);
|
|
|
|
return newProfile;
|
2024-06-25 12:36:40 +01:00
|
|
|
}
|
2024-06-27 21:05:54 +01:00
|
|
|
return clazz.cast(profile);
|
2024-06-25 12:36:40 +01:00
|
|
|
}
|
|
|
|
}
|