feat(board): add shared physical quest boards
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package games.dmg.spigotquestboard;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
final class BoardRegistry {
|
||||
private final BoardRepository repository;
|
||||
private Map<BoardId, RegisteredBoard> boards;
|
||||
|
||||
BoardRegistry(BoardRepository repository) throws IOException {
|
||||
this.repository = Objects.requireNonNull(repository, "repository");
|
||||
boards = index(repository.load());
|
||||
}
|
||||
|
||||
synchronized BoardRegistrationResult register(RegisteredBoard board) throws IOException {
|
||||
Objects.requireNonNull(board, "board");
|
||||
if (boards.containsKey(board.id())) {
|
||||
return BoardRegistrationResult.ALREADY_REGISTERED;
|
||||
}
|
||||
Map<BoardId, RegisteredBoard> candidate = new LinkedHashMap<>(boards);
|
||||
candidate.put(board.id(), board);
|
||||
repository.save(new BoardState(Set.copyOf(candidate.values())));
|
||||
boards = Map.copyOf(candidate);
|
||||
return BoardRegistrationResult.CREATED;
|
||||
}
|
||||
|
||||
synchronized boolean contains(BoardId id) {
|
||||
return boards.containsKey(id);
|
||||
}
|
||||
|
||||
synchronized int size() {
|
||||
return boards.size();
|
||||
}
|
||||
|
||||
private static Map<BoardId, RegisteredBoard> index(BoardState state) throws IOException {
|
||||
Map<BoardId, RegisteredBoard> indexed = new LinkedHashMap<>();
|
||||
for (RegisteredBoard board : state.boards()) {
|
||||
if (indexed.put(board.id(), board) != null) {
|
||||
throw new IOException("Duplicate quest board location: " + board.id());
|
||||
}
|
||||
}
|
||||
return Map.copyOf(indexed);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user