APIv3/src/main/java/net/frozenorb/apiv3/model/Rank.java
2016-06-26 19:19:34 -04:00

90 lines
2.7 KiB
Java

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<Rank> ranksCollection = APIv3.getDatabase().getCollection("ranks", Rank.class);
private static Map<String, Rank> rankIdCache = null;
private static List<Rank> 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<Rank> findAll() {
return ImmutableList.copyOf(rankCache);
}
public static Rank findById(String id) {
return rankIdCache.get(id);
}
static {
APIv3.getVertxInstance().setPeriodic(TimeUnit.MINUTES.toMillis(1), (id) -> updateCache());
}
public static void updateCache() {
ranksCollection.find().into(new LinkedList<>(), (ranks, error) -> {
if (error != null) {
error.printStackTrace();
return;
}
Map<String, Rank> working = new HashMap<>();
for (Rank rank : ranks) {
working.put(rank.getId(), rank);
}
rankIdCache = working;
rankCache = 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<Void> callback) {
rankCache.add(this);
rankIdCache.put(id, this);
ranksCollection.insertOne(this, callback);
}
public void delete(SingleResultCallback<DeleteResult> callback) {
rankCache.remove(this);
rankIdCache.remove(id);
ranksCollection.deleteOne(new Document("_id", id), callback);
}
}