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; /** * @author Fascinated (fascinated7) */ @Getter public abstract class ProfileHolder { /** * The profiles for the holder */ private final Map profiles = new HashMap<>(); /** * Gets a profile for the holder * * @param clazz The class of the profile * @param The type of the profile * @return The profile */ public abstract T getProfile(Class clazz); /** * Gets the profiles for the holder * using the provided document * * @return the profiles */ @SneakyThrows protected T getProfileFromDocument(Class clazz, Document document) { Serializable profile = getProfiles().get(clazz.getSimpleName()); 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 = profiles.isEmpty() ? new org.bson.Document() : profiles.get(clazz.getSimpleName(), new org.bson.Document()); newProfile.load(profileDocument, BatApplication.GSON); getProfiles().put(clazz.getSimpleName(), newProfile); return newProfile; } return clazz.cast(profile); } }