|
| 1 | +package io.github.moulberry.repo.data; |
| 2 | + |
| 3 | +import io.github.moulberry.repo.IReloadable; |
| 4 | +import io.github.moulberry.repo.NEURepoFile; |
| 5 | +import io.github.moulberry.repo.NEURepository; |
| 6 | +import io.github.moulberry.repo.NEURepositoryException; |
| 7 | +import io.github.moulberry.repo.util.NEUId; |
| 8 | +import lombok.Cleanup; |
| 9 | +import lombok.Getter; |
| 10 | +import lombok.Value; |
| 11 | + |
| 12 | +import java.util.List; |
| 13 | +import java.util.Map; |
| 14 | +import java.util.Objects; |
| 15 | +import java.util.function.Function; |
| 16 | +import java.util.regex.Matcher; |
| 17 | +import java.util.regex.Pattern; |
| 18 | +import java.util.stream.Collectors; |
| 19 | +import java.util.stream.Stream; |
| 20 | + |
| 21 | +@Getter |
| 22 | +public class ItemOverlays implements IReloadable { |
| 23 | + |
| 24 | + List<ItemOverlayFile> overlays; |
| 25 | + |
| 26 | + public static ItemOverlays forRepo(NEURepository repository) { |
| 27 | + ItemOverlays overlays = new ItemOverlays(); |
| 28 | + repository.registerReloadListener(overlays); |
| 29 | + return overlays; |
| 30 | + } |
| 31 | + |
| 32 | + @Override |
| 33 | + public void reload(NEURepository repository) throws NEURepositoryException { |
| 34 | + @Cleanup Stream<NEURepoFile> files = repository.tree("itemsOverlay"); |
| 35 | + overlays = files |
| 36 | + .filter(NEURepoFile::isFile) |
| 37 | + .map(file -> { |
| 38 | + Matcher matcher = PATH_PATTERN.matcher(file.getPath()); |
| 39 | + if (matcher.matches()) { |
| 40 | + int version = Integer.parseInt(matcher.group(1)); |
| 41 | + String name = matcher.group(2); |
| 42 | + return new ItemOverlayFile(file, version, name); |
| 43 | + } |
| 44 | + return null; |
| 45 | + }) |
| 46 | + .filter(Objects::nonNull) |
| 47 | + .collect(Collectors.toList()); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * @param version the highest supported version |
| 52 | + * @return a map of item ids to their most up-to-date overlay file that is still readable. |
| 53 | + */ |
| 54 | + public Map<@NEUId String, ItemOverlayFile> getMostUpToDateCompatibleWith(int version) { |
| 55 | + return overlays.stream() |
| 56 | + .filter(it -> it.version <= version) |
| 57 | + .collect(Collectors.toMap(ItemOverlayFile::getItemId, Function.identity(), (a, b) -> a.version > b.version ? a : b)); |
| 58 | + } |
| 59 | + |
| 60 | + @Value |
| 61 | + public static class ItemOverlayFile { |
| 62 | + NEURepoFile file; |
| 63 | + int version; |
| 64 | + @NEUId |
| 65 | + String itemId; |
| 66 | + } |
| 67 | + |
| 68 | + private static final Pattern PATH_PATTERN = Pattern.compile("itemsOverlay/([0-9]+)/(.+)\\.snbt"); |
| 69 | +} |
0 commit comments