APIv3/src/main/java/net/frozenorb/apiv3/model/Rank.java

88 lines
2.5 KiB
Java
Raw Normal View History

2016-06-16 16:29:33 +02:00
package net.frozenorb.apiv3.model;
2016-03-21 23:28:17 +01:00
2016-05-09 05:18:55 +02:00
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;
2016-06-16 06:08:44 +02:00
import fr.javatic.mongo.jacksonCodec.Entity;
import fr.javatic.mongo.jacksonCodec.objectId.Id;
2016-03-21 23:28:17 +01:00
import lombok.Getter;
import net.frozenorb.apiv3.APIv3;
import org.bson.Document;
2016-03-21 23:28:17 +01:00
2016-06-01 20:23:37 +02:00
import java.util.HashMap;
import java.util.LinkedList;
2016-06-01 20:23:37 +02:00
import java.util.List;
import java.util.Map;
2016-05-09 05:18:55 +02:00
import java.util.concurrent.TimeUnit;
2016-04-27 02:46:34 +02:00
2016-06-16 06:08:44 +02:00
@Entity
2016-03-21 23:28:17 +01:00
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;
2016-05-09 05:18:55 +02:00
2016-03-21 23:28:17 +01:00
@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;
2016-04-08 13:12:31 +02:00
public static List<Rank> findAll() {
return rankCache;
2016-04-08 13:12:31 +02:00
}
2016-03-21 23:28:17 +01:00
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<String, Rank> working = new HashMap<>();
for (Rank rank : ranks) {
working.put(rank.getId(), rank);
}
rankIdCache = ImmutableMap.copyOf(working);
rankCache = ImmutableList.copyOf(ranks);
});
2016-04-27 02:46:34 +02:00
}
private Rank() {} // For Jackson
2016-03-21 23:28:17 +01:00
2016-04-08 13:12:31 +02:00
public Rank(String id, int weight, String displayName, String gameColor, String websiteColor, boolean staffRank) {
2016-03-21 23:28:17 +01:00
this.id = id;
this.weight = weight;
this.displayName = displayName;
this.gameColor = gameColor;
this.websiteColor = websiteColor;
2016-04-08 13:12:31 +02:00
this.staffRank = staffRank;
2016-03-21 23:28:17 +01:00
}
public void insert(SingleResultCallback<Void> callback) {
ranksCollection.insertOne(this, callback);
}
public void delete(SingleResultCallback<DeleteResult> callback) {
ranksCollection.deleteOne(new Document("_id", id), callback);
}
2016-03-21 23:28:17 +01:00
}