package net.frozenorb.apiv3.model; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.mongodb.async.SingleResultCallback; 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 org.bson.Document; import java.util.HashMap; import java.util.LinkedList; 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 rankIdCache = null; private static List rankCache = null; @Getter @Id private String id; @Getter private String inheritsFromId; @Getter private int weight; @Getter private String displayName; @Getter private String gameColor; @Getter private String websiteColor; @Getter private boolean staffRank; public static List findAll() { return rankCache; } public static Rank findById(String id) { return rankIdCache.get(id); } static { updateCache(); APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache()); } private static void updateCache() { ranksCollection.find().into(new LinkedList<>(), (ranks, error) -> { if (error != null) { error.printStackTrace(); return; } Map working = new HashMap<>(); for (Rank rank : ranks) { working.put(rank.getId(), rank); } rankIdCache = ImmutableMap.copyOf(working); rankCache = ImmutableList.copyOf(ranks); }); } private Rank() {} // For Jackson public Rank(String id, String inheritsFromId, int weight, String displayName, String gameColor, String websiteColor, boolean staffRank) { this.id = id; this.inheritsFromId = inheritsFromId; this.weight = weight; this.displayName = displayName; this.gameColor = gameColor; this.websiteColor = websiteColor; this.staffRank = staffRank; } public void insert(SingleResultCallback callback) { rankCache.add(this); rankIdCache.put(id, this); ranksCollection.insertOne(this, callback); } public void delete(SingleResultCallback callback) { rankCache.remove(this); rankIdCache.remove(id); ranksCollection.deleteOne(new Document("_id", id), callback); } }