package ru.dbotthepony.mc.otm.data

import com.google.gson.JsonObject
import com.google.gson.JsonParseException
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.advancements.critereon.ItemPredicate

object ItemPredicateCodec : Codec<ItemPredicate> {
	override fun <T : Any> encode(input: ItemPredicate, ops: DynamicOps<T>, prefix: T): DataResult<T> {
		return DataResult.success(JsonOps.INSTANCE.convertTo(ops, input.serializeToJson().let { if (it is JsonObject) it.getRidOfNulls() else it }))
	}

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