package net.frozenorb.apiv3.models; import com.google.common.collect.ImmutableList; import lombok.Getter; import net.frozenorb.apiv3.APIv3; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Id; import org.mongodb.morphia.annotations.Indexed; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @Entity(value = "ranks", noClassnameStored = true) public final class Rank { private static Map rankCache = null; private static List rankAltCache = null; private static long rankCacheUpdated = 0; @Getter @Id private String id; @Getter private int weight; @Getter private String displayName; @Getter private String gameColor; @Getter private String websiteColor; @Getter @Indexed private boolean staffRank; public static Rank byId(String id) { updateCacheIfNeeded(); return rankCache.get(id); } public static List values() { updateCacheIfNeeded(); return ImmutableList.copyOf(rankAltCache); } public Rank() {} // For Morphia public Rank(String id, int weight, String displayName, String gameColor, String websiteColor, boolean staffRank) { this.id = id; this.weight = weight; this.displayName = displayName; this.gameColor = gameColor; this.websiteColor = websiteColor; this.staffRank = staffRank; } public void delete() { APIv3.getDatastore().delete(this); } private static void updateCacheIfNeeded() { if (rankCache == null || (System.currentTimeMillis() - rankCacheUpdated) > TimeUnit.MINUTES.toMillis(1)) { Map working = new HashMap<>(); List workingAlt = new ArrayList<>(); for (Rank rank : APIv3.getDatastore().createQuery(Rank.class).order("weight").asList()) { working.put(rank.getId(), rank); workingAlt.add(rank); } rankCache = working; rankAltCache = workingAlt; rankCacheUpdated = System.currentTimeMillis(); } } }