package ru.dbotthepony.mc.otm.data

import com.mojang.datafixers.util.Pair
import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult
import com.mojang.serialization.DynamicOps
import ru.dbotthepony.mc.otm.core.math.Decimal

object DecimalCodec : Codec<Decimal> {
	override fun <T : Any> encode(input: Decimal, ops: DynamicOps<T>, prefix: T): DataResult<T> {
		return DataResult.success(ops.createString(input.toString()))
	}

	override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Decimal, T>> {
		val result = ops.getStringValue(input).flatMap {
			try {
				DataResult.success(Pair(Decimal(it), ops.empty()))
			} catch (err: NumberFormatException) {
				DataResult.error { "Not a valid number for converting into Decimal: $it" }
			}
		}

		if (result.result().isPresent) {
			return result
		}

		return ops.getNumberValue(input).flatMap {
			DataResult.success(Pair(Decimal(it.toString()), ops.empty()))
		}
	}
}
