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

56 lines
1.7 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-07-01 21:20:39 +01:00
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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-07-01 21:20:39 +01:00
private static final Logger log = LoggerFactory.getLogger(ProfileHolder.class);
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());
2024-07-01 21:20:39 +01:00
log.info("instance of profiles: {}", document.get("profiles").getClass().getSimpleName());
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 19:40:32 +01:00
newProfile.load(profileDocument == null ? new Document() : 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
}
}