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.network.chat.Component

object ComponentCodec : Codec<Component> {
	override fun <T : Any> encode(input: Component, ops: DynamicOps<T>, prefix: T): DataResult<T> {
		return DataResult.success(JsonOps.INSTANCE.convertTo(ops, Component.Serializer.toJsonTree(input)))
	}

	override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Component, T>> {
		val value = ops.convertTo(JsonOps.INSTANCE, input)

		try {
			return DataResult.success(Pair(Component.Serializer.fromJson(value), ops.empty()))
		} catch (err: JsonSyntaxException) {
			return DataResult.error { "Error decoding component: ${err.message}" }
		}
	}
}
