package ru.dbotthepony.mc.otm.compat.mekanism

import mekanism.api.math.FloatingLong
import ru.dbotthepony.mc.otm.core.math.Decimal
import java.math.BigInteger

private val LONG_OVERFLOW = (BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.TWO) * Decimal.PRECISION_POW_BI
private val LONG_OVERFLOW1 = BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.ONE

fun Decimal.toFloatingLong(): FloatingLong {
	if (isNegative) {
		// Floating long can't be negative
		return FloatingLong.ZERO
	}

	if (whole >= LONG_OVERFLOW1) {
		return FloatingLong.MAX_VALUE
	}

	return FloatingLong.create(whole.toLong(), (fractionalFloat * 10_000.0).toInt().toShort())
}

fun FloatingLong.toDecimal(): Decimal {
	var conv = BigInteger.valueOf(value) * Decimal.PRECISION_POW_BI + BigInteger.valueOf((decimal.toDouble() / 10_000.0 * Decimal.PRECISION_DOUBLE).toLong())

	// Overflow
	if (value < 0L) {
		conv += LONG_OVERFLOW
	}

	return Decimal.raw(conv)
}
