package ru.dbotthepony.mc.otm.data

import com.google.gson.JsonSyntaxException
import com.mojang.datafixers.util.Pair
import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult
import com.mojang.serialization.DynamicOps
import com.mojang.serialization.JsonOps
import net.minecraft.world.item.crafting.Ingredient

object IngredientCodec : Codec<Ingredient> {
	override fun <T : Any> encode(input: Ingredient, ops: DynamicOps<T>, prefix: T): DataResult<T> {
		return DataResult.success(JsonOps.INSTANCE.convertTo(ops, input.toJson()))
	}

	override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Ingredient, T>> {
		try {
			return DataResult.success(Pair(Ingredient.fromJson(ops.convertTo(JsonOps.INSTANCE, input)), ops.empty()))
		} catch (err: JsonSyntaxException) {
			return DataResult.error { "Error decoding Ingredient: ${err.message}" }
		}
	}
}
