package net.frozenorb.apiv3.model; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; import com.mongodb.async.client.MongoCollection; import com.mongodb.client.result.DeleteResult; import fr.javatic.mongo.jacksonCodec.Entity; import fr.javatic.mongo.jacksonCodec.objectId.Id; import lombok.Getter; import net.frozenorb.apiv3.APIv3; import net.frozenorb.apiv3.unsorted.BlockingCallback; import net.frozenorb.apiv3.util.SyncUtils; import org.bson.Document; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @Entity public final class Rank { private static final MongoCollection ranksCollection = APIv3.getDatabase().getCollection("ranks", Rank.class); 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 private boolean staffRank; public static List findAll() { updateCacheIfNeeded(); return ImmutableList.copyOf(rankAltCache); } public static Rank findById(String id) { updateCacheIfNeeded(); return rankCache.get(id); } public Rank() {} // For Jackson 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; } private static void updateCacheIfNeeded() { if (rankCache == null || (System.currentTimeMillis() - rankCacheUpdated) > TimeUnit.MINUTES.toMillis(1)) { Map working = new HashMap<>(); List workingAlt = new ArrayList<>(); List allRanks = SyncUtils.blockMulti(ranksCollection.find()); allRanks.sort((a, b) -> Ints.compare(a.getWeight(), b.getWeight())); for (Rank rank : allRanks) { working.put(rank.getId(), rank); workingAlt.add(rank); } rankCache = working; rankAltCache = workingAlt; rankCacheUpdated = System.currentTimeMillis(); } } public void insert() { BlockingCallback callback = new BlockingCallback<>(); ranksCollection.insertOne(this, callback); callback.get(); } public void delete() { BlockingCallback callback = new BlockingCallback<>(); ranksCollection.deleteOne(new Document("_id", id), callback); callback.get(); } }