summaryrefslogtreecommitdiff
path: root/src/main/java/lv/enes/mc/eris_alchemy/utils/IngredientProvider.java
blob: 6390c88975d6200df4e656415af3d3008f5d6da4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package lv.enes.mc.eris_alchemy.utils;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.crafting.Ingredient;

import java.lang.reflect.Type;
import java.util.function.Supplier;

public class IngredientProvider implements JsonDeserializer<Supplier<Ingredient>> {
	public static Supplier<Ingredient> deserialize(JsonElement el) {
		if (el.isJsonObject()) {
			return () -> ItemUtils.itemStackFromJson(el.getAsJsonObject()).map(Ingredient::of).orElse(Ingredient.EMPTY);
		} else if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) {
			return deserialize(el.getAsString().strip());
		} else {
			throw new JsonParseException("Every ingredient should be an object or a string");
		}
	}

	public static Supplier<Ingredient> deserialize(String str) {
		if (str.startsWith("#")) {
			var tag = TagKey.create(Registries.ITEM, new ResourceLocation(str.substring(1).strip()));
			return () -> Ingredient.of(tag);
		} else {
			return () -> Ingredient.of(ItemUtils.get(new ResourceLocation(str)));
		}
	}

	@Override
	public Supplier<Ingredient> deserialize(
			JsonElement el,
			Type t,
			JsonDeserializationContext c
	) {
		return IngredientProvider.deserialize(el);
	}
}