42 lines
1.3 KiB
Java
42 lines
1.3 KiB
Java
package games.dmg.spigotbase;
|
|
|
|
import java.io.IOException;
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.UUID;
|
|
import java.util.function.UnaryOperator;
|
|
|
|
final class PocketBaseStateManager {
|
|
private final YamlPocketBaseRepository repository;
|
|
private final Map<UUID, PocketBaseState> states;
|
|
|
|
PocketBaseStateManager(YamlPocketBaseRepository repository) throws IOException {
|
|
this.repository = repository;
|
|
this.states = new HashMap<>(repository.load());
|
|
}
|
|
|
|
PocketBaseState state(UUID ownerId) {
|
|
return states.getOrDefault(ownerId, PocketBaseState.locked(ownerId));
|
|
}
|
|
|
|
Map<UUID, PocketBaseState> knownStates() {
|
|
return Map.copyOf(states);
|
|
}
|
|
|
|
PocketBaseState updateAndSave(
|
|
UUID ownerId,
|
|
UnaryOperator<PocketBaseState> operation
|
|
) throws IOException {
|
|
PocketBaseState updated = operation.apply(state(ownerId));
|
|
if (!updated.ownerId().equals(ownerId)) {
|
|
throw new IllegalArgumentException("Pocket Base owner ID cannot change");
|
|
}
|
|
Map<UUID, PocketBaseState> proposed = new HashMap<>(states);
|
|
proposed.put(ownerId, updated);
|
|
repository.save(proposed);
|
|
states.clear();
|
|
states.putAll(proposed);
|
|
return updated;
|
|
}
|
|
}
|