|
| 1 | +package com.robertx22.test; |
| 2 | + |
| 3 | +import com.google.common.base.Preconditions; |
| 4 | +import com.google.common.base.Supplier; |
| 5 | +import com.google.gson.JsonObject; |
| 6 | + |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.List; |
| 9 | + |
| 10 | +public abstract class ModSchema<T> { |
| 11 | + |
| 12 | + public String id; |
| 13 | + |
| 14 | + public Supplier<ModSchema> sup; |
| 15 | + |
| 16 | + public List<SchemaPart> parts = new ArrayList<>(); |
| 17 | + public List<ModSchema> schemas = new ArrayList<>(); |
| 18 | + |
| 19 | + public ModSchema<T> createNewInstance() { |
| 20 | + return sup.get(); |
| 21 | + } |
| 22 | + |
| 23 | + public ModSchema(ModSchema parent, String id, Supplier<ModSchema> sup) { |
| 24 | + this.id = id; |
| 25 | + this.sup = sup; |
| 26 | + if (parent == null && this instanceof MainSchema) { |
| 27 | + // main schemas dont have a parent |
| 28 | + } else { |
| 29 | + Preconditions.checkArgument(parent != null); |
| 30 | + parent.schemas.add(this); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + |
| 35 | + public JsonObject toJson() { |
| 36 | + JsonObject json = new JsonObject(); |
| 37 | + for (SchemaPart part : parts) { |
| 38 | + part.save(json); |
| 39 | + } |
| 40 | + for (ModSchema part : schemas) { |
| 41 | + JsonObject inner = part.toJson(); |
| 42 | + json.add(part.id, inner); |
| 43 | + } |
| 44 | + |
| 45 | + return json; |
| 46 | + } |
| 47 | + |
| 48 | + public void load(MainSchema main, JsonObject json) { |
| 49 | + for (SchemaPart part : parts) { |
| 50 | + if (!json.has(part.id)) { |
| 51 | + if (part.isOptional()) { |
| 52 | + part.object = part.optionalValue; |
| 53 | + } else { |
| 54 | + throw new RuntimeException("Datapack error: " + part.id + " field inside " + main.id + " is missing and not optional!"); |
| 55 | + } |
| 56 | + } |
| 57 | + var loaded = json.get(part.id); |
| 58 | + part.load(main, loaded); |
| 59 | + } |
| 60 | + for (ModSchema part : schemas) { |
| 61 | + JsonObject inner = json.getAsJsonObject(part.id); |
| 62 | + part.load(main, inner); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments