Files
purpur-quest-board/src/main/java/games/dmg/spigotquestboard/BoardRegistry.java
T
dmg 72e58383a2
Release / release (push) Successful in 2m29s
CI / build (push) Successful in 1m9s
feat(board): add readable physical board signs
2026-09-05 09:26:45 -04:00

63 lines
2.1 KiB
Java

package games.dmg.spigotquestboard;
import java.io.IOException;
import java.util.Collection;
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 {
return registerAll(Set.of(Objects.requireNonNull(board, "board")));
}
synchronized BoardRegistrationResult registerAll(Collection<RegisteredBoard> additions)
throws IOException {
Objects.requireNonNull(additions, "additions");
Map<BoardId, RegisteredBoard> candidate = new LinkedHashMap<>(boards);
for (RegisteredBoard board : additions) {
Objects.requireNonNull(board, "board");
if (candidate.putIfAbsent(board.id(), board) != null) {
return BoardRegistrationResult.ALREADY_REGISTERED;
}
}
if (additions.isEmpty()) {
return BoardRegistrationResult.CREATED;
}
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();
}
synchronized Map<BoardId, RegisteredBoard> registeredBoards() {
return Map.copyOf(boards);
}
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);
}
}