package vg.civcraft.mc.civmodcore.locations.chunkmeta.block.fallback;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bukkit.Location;

import vg.civcraft.mc.civmodcore.locations.chunkmeta.XZWCoord;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.block.BlockBasedChunkMeta;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.block.BlockDataObject;

public class SingleBlockTracker<D extends BlockDataObject<D>> {

	private Map<XZWCoord, Map<Location, D>> blocks;

	public SingleBlockTracker() {
		blocks = new HashMap<>();
	}

	public void putBlock(D data, short worldID) {
		Map<Location, D> existing = blocks.computeIfAbsent(toCoord(data.getLocation(), worldID), s -> new HashMap<>());
		existing.put(data.getLocation(), data);
	}

	public D getBlock(Location location, short worldID) {
		Map<Location, D> existing = blocks.get(toCoord(location, worldID));
		if (existing == null) {
			return null;
		}
		return existing.get(location);
	}

	public D removeBlock(Location location, short worldID) {
		Map<Location, D> existing = blocks.get(toCoord(location, worldID));
		if (existing == null) {
			return null;
		}
		return existing.remove(location);
	}

	public Collection<D> getAllForChunkAndRemove(XZWCoord chunk) {
		return blocks.remove(chunk).values();
	}

	private static XZWCoord toCoord(Location location, short worldID) {
		return new XZWCoord(BlockBasedChunkMeta.toChunkCoord(location.getBlockX()),
				BlockBasedChunkMeta.toChunkCoord(location.getBlockZ()), worldID);
	}

	public Collection<D> getAll() {
		List<D> result = new ArrayList<>();
		for (Map<Location, D> chunkMap : blocks.values()) {
			for (D data : chunkMap.values()) {
				result.add(data);
			}
		}
		return result;
	}

}

@@ -121,16 +121,46 @@
 ection;%0A
+import java.util.Collections;%0A
 import j
@@ -1349,35 +1349,137 @@
 %7B%0A%09%09
-return blocks.remove(chunk)
+Map%3CLocation, D%3E removed = blocks.remove(chunk);%0A%09%09if (removed == null) %7B%0A%09%09%09return Collections.emptyList();%0A%09%09%7D%0A%09%09return removed
 .val

Fix NPE in SingleBlockTracker