summaryrefslogtreecommitdiff
path: root/src/main/java/lv/enes/mc/eris_alchemy/utils/ItemUtils.java
blob: ccf8b438ec2aea35a8c1247c62a4521faeb6737a (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
44
45
46
47
48
49
50
51
52
53
package lv.enes.mc.eris_alchemy.utils;

import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import lv.enes.mc.eris_alchemy.ErisAlchemy;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.ShapedRecipe;
import net.minecraft.world.level.ItemLike;

import java.util.Optional;

public final class ItemUtils {
	public static Item get(ResourceLocation id) {
		return BuiltInRegistries.ITEM.get(id);
	}

	public static <I extends ItemLike> ResourceLocation getId(Holder<I> holder) {
		return getId(holder.value());
	}

	public static ResourceLocation getId(ItemLike item) {
		return BuiltInRegistries.ITEM.getKey(item.asItem());
	}

	public static ResourceLocation getId(ItemStack stack) {
		return getId(stack.getItem());
	}

	public static Optional<Ingredient> ingredientFromJson(JsonObject json) {
		try {
			return Optional.of(Ingredient.fromJson(json, false));
		} catch (JsonSyntaxException ex) {
			ErisAlchemy.LOGGER.warn("Exception while trying to parse ingredient from JSON: {}", json, ex);
			return Optional.empty();
		}
	}

	public static Optional<ItemStack> itemStackFromJson(JsonObject json) {
		try {
			return Optional.of(ShapedRecipe.itemStackFromJson(json));
		} catch (JsonSyntaxException ex) {
			ErisAlchemy.LOGGER.warn("Exception while trying to parse item stack from JSON: {}", json, ex);
			return Optional.empty();
		}
	}

	private ItemUtils() {}
}