Amount.kt

/*
 * This file is part of GNU Taler
 * (C) 2020 Taler Systems S.A.
 *
 * GNU Taler is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3, or (at your option) any later version.
 *
 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

package net.taler.common

import android.icu.number.NumberFormatter
import android.icu.number.Precision
import android.icu.text.DecimalFormatSymbols
import android.icu.util.Currency
import android.icu.util.ULocale
import android.os.Build
import androidx.annotation.RequiresApi
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.Serializer
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.math.RoundingMode
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.Locale
import kotlin.math.floor
import kotlin.math.pow

class AmountParserException(msg: String? = null, cause: Throwable? = null) :
    Exception(msg, cause)

class AmountOverflowException(msg: String? = null, cause: Throwable? = null) :
    Exception(msg, cause)

@Serializable(with = KotlinXAmountSerializer::class)
data class Amount(
    /**
     * name of the currency using either a three-character ISO 4217 currency code,
     * or a regional currency identifier starting with a "*" followed by at most 10 characters.
     * ISO 4217 exponents in the name are not supported,
     * although the "fraction" is corresponds to an ISO 4217 exponent of 6.
     */
    val currency: String,

    /**
     * The integer part may be at most 2^52.
     * Note that "1" here would correspond to 1 EUR or 1 USD, depending on currency, not 1 cent.
     */
    val value: Long,

    /**
     * Unsigned 32 bit fractional value to be added to value representing
     * an additional currency fraction, in units of one hundred millionth (1e-8)
     * of the base currency value.  For example, a fraction
     * of 50_000_000 would correspond to 50 cents.
     */
    val fraction: Int,

    /**
     * Currency specification for amount
     */
    val spec: CurrencySpecification? = null,
) : Comparable<Amount> {

    companion object {

        const val DEFAULT_INPUT_DECIMALS = 2
        private const val FRACTIONAL_BASE: Int = 100000000 // 1e8

        private val REGEX_CURRENCY = Regex("""^[-_*A-Za-z0-9]{1,12}$""")
        private val REGEX_AMOUNT = Regex("[0-9]+(\\.[0-9]{0,8})?")
        val MAX_VALUE: Long = 2.0.pow(52).toLong()
        private const val MAX_FRACTION_LENGTH = 8
        const val MAX_FRACTION: Int = 99_999_999

        fun zero(currency: String): Amount {
            return Amount(checkCurrency(currency), 0, 0)
        }

        fun fromJSONString(str: String): Amount {
            val split = str.split(":")
            if (split.size != 2) throw AmountParserException("Invalid Amount Format")
            return fromString(split[0], split[1])
        }

        fun fromString(currency: String, str: String): Amount {
            if (!REGEX_AMOUNT.matches(str))
                throw AmountParserException("Invalid Amount Format")
            // value
            val valueSplit = str.split(".")
            if (valueSplit.size > 2) throw AmountParserException("Invalid Amount Format")
            val value = checkValue(valueSplit[0].toLongOrNull())
            // fraction
            val fraction: Int = if (valueSplit.size > 1) {
                val fractionStr = valueSplit[1]
                if (fractionStr.length > MAX_FRACTION_LENGTH)
                    throw AmountParserException("Fraction $fractionStr too long")
                checkFraction(fractionStr.getFraction())
            } else 0
            return Amount(checkCurrency(currency), value, fraction)
        }

        fun isValidAmountStr(str: String): Boolean {
            if (!REGEX_AMOUNT.matches(str)) return false
            if (str.count { it == '.' } > 1) return false
            val split = str.split(".")
            try {
                checkValue(split[0].toLongOrNull())
            } catch (e: AmountParserException) {
                return false
            }
            // also check fraction, if it exists
            if (split.size > 1) {
                val fractionStr = split[1]
                if (fractionStr.length > MAX_FRACTION_LENGTH) return false
                val fraction = fractionStr.getFraction() ?: return false
                return fraction <= MAX_FRACTION
            }
            return true
        }

        private fun String.getFraction(): Int? {
            return padEnd(MAX_FRACTION_LENGTH, '0').toIntOrNull()
        }

        fun min(currency: String): Amount = Amount(currency, 0, 1)
        fun max(currency: String): Amount = Amount(currency, MAX_VALUE, MAX_FRACTION)


        internal fun checkCurrency(currency: String): String {
            if (!REGEX_CURRENCY.matches(currency))
                throw AmountParserException("Invalid currency: $currency")
            return currency
        }

        internal fun checkValue(value: Long?): Long {
            if (value == null || value < 0 || value > MAX_VALUE)
                throw AmountParserException("Value $value greater than $MAX_VALUE")
            return value
        }

        internal fun checkFraction(fraction: Int?): Int {
            if (fraction == null || fraction < 0 || fraction > MAX_FRACTION)
                throw AmountParserException("Fraction $fraction greater than $MAX_FRACTION")
            return fraction
        }

    }

    val amountStr: String
        get() = if (fraction == 0) "$value" else {
            var f = fraction
            var fractionStr = ""
            while (f > 0) {
                fractionStr += f / (FRACTIONAL_BASE / 10)
                f = (f * 10) % FRACTIONAL_BASE
            }
            "$value.$fractionStr"
        }

    operator fun plus(other: Amount): Amount {
        check(currency == other.currency) { "Can only subtract from same currency" }
        val resultValue =
            value + other.value + floor((fraction + other.fraction).toDouble() / FRACTIONAL_BASE).toLong()
        if (resultValue > MAX_VALUE)
            throw AmountOverflowException()
        val resultFraction = (fraction + other.fraction) % FRACTIONAL_BASE
        return Amount(currency, resultValue, resultFraction, spec ?: other.spec)
    }

    operator fun times(factor: Int): Amount {
        // TODO consider replacing with a faster implementation
        if (factor == 0) return zero(currency).withSpec(spec)
        var result = this
        for (i in 1 until factor) result += this
        return result
    }

    fun withCurrency(currency: String): Amount {
        return Amount(
            checkCurrency(currency),
            this.value,
            this.fraction,
            if (currency == this.currency) spec else null,
        )
    }

    fun withSpec(spec: CurrencySpecification?) = copy(spec = spec)

    operator fun minus(other: Amount): Amount {
        check(currency == other.currency) { "Can only subtract from same currency" }
        var resultValue = value
        var resultFraction = fraction
        if (resultFraction < other.fraction) {
            if (resultValue < 1L)
                throw AmountOverflowException()
            resultValue--
            resultFraction += FRACTIONAL_BASE
        }
        check(resultFraction >= other.fraction)
        resultFraction -= other.fraction
        if (resultValue < other.value)
            throw AmountOverflowException()
        resultValue -= other.value
        return Amount(currency, resultValue, resultFraction, spec ?: other.spec)
    }

    fun isZero(): Boolean {
        return value == 0L && fraction == 0
    }

    fun toJSONString(): String {
        return "$currency:$amountStr"
    }

    override fun toString() = toString(
        showSymbol = true,
        negative = false,
    )

    fun addInputDigit(c: Char): Amount? = c.digitToIntOrNull()?.let { digit ->
        try {
            val value = amountStr.toBigDecimal()
            val decimals = spec?.numFractionalInputDigits ?: DEFAULT_INPUT_DECIMALS
            fromString(
                currency,
                // some real math!
                ((value * 10.0.toBigDecimal().setScale(decimals))
                        + (digit.toBigDecimal().setScale(decimals)
                        / 10.0.toBigDecimal().pow(decimals))).toString()
            )
        } catch (e: AmountParserException) { null }
    }

    fun removeInputDigit(): Amount? = try {
        val decimals = spec?.numFractionalInputDigits ?: DEFAULT_INPUT_DECIMALS
        val value = amountStr.toBigDecimal().setScale(decimals + 1, RoundingMode.FLOOR)
        fromString(
            currency,
            // more math!
            (value / "10.0".toBigDecimal()).setScale(decimals, RoundingMode.FLOOR).toString()
        )
    } catch (e: AmountParserException) { null }

    fun toString(
        showSymbol: Boolean = true,
        negative: Boolean = false,
        symbols: java.text.DecimalFormatSymbols = DecimalFormat().decimalFormatSymbols,
        locale: Locale = Locale.getDefault(),
    ): String {
        val amount = (if (negative) "-$amountStr" else amountStr).toBigDecimal()
        val symbol = spec?.symbol ?: currency
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // In newer phones > 2019, do full, locale-based formatting
            val uLocale = ULocale.forLocale(locale)
            // Language-only app locales (e.g. "en") have no regional currency.
            // Use a neutral template; the actual Taler currency symbol replaces it below.
            val blueprintCurrency = Currency.getInstance(uLocale) ?: Currency.getInstance("XXX")
            NumberFormatter.with()
                .unit(blueprintCurrency)
                .unitWidth(
                    if (showSymbol) {
                        if (symbol.length > 1)
                            NumberFormatter.UnitWidth.ISO_CODE else
                            NumberFormatter.UnitWidth.SHORT
                    } else NumberFormatter.UnitWidth.HIDDEN)
                .locale(uLocale)
                .symbols(symbols.toIcu(locale))
                .precision(Precision.minMaxFraction(
                    spec?.numFractionalTrailingZeroDigits ?: 2,
                    MAX_FRACTION_LENGTH))
                .format(amount)
                .toString()
                .replace(blueprintCurrency.currencyCode, symbol)
                .replace(blueprintCurrency.symbol, symbol)
        } else {
            // In older phones <= 2019, always do "$CURRENCY $AMOUNT"
            val s = symbols.clone() as java.text.DecimalFormatSymbols
            val format = NumberFormat.getInstance()
            format.minimumFractionDigits = spec?.numFractionalTrailingZeroDigits ?: 2
            format.maximumFractionDigits = MAX_FRACTION_LENGTH
            (format as DecimalFormat).decimalFormatSymbols = s

            val fmt = format.format(amount)
            if (showSymbol) {
                "$currency $fmt"
            } else {
                fmt
            }
        }
    }

    override fun equals(other: Any?): Boolean {
        return other is Amount && (value == other.value && fraction == other.fraction && currency == other.currency)
    }

    override fun compareTo(other: Amount): Int {
        check(currency == other.currency) { "Can only compare amounts with the same currency" }
        when {
            value == other.value -> {
                if (fraction < other.fraction) return -1
                if (fraction > other.fraction) return 1
                return 0
            }
            value < other.value -> return -1
            else -> return 1
        }
    }
}

@OptIn(ExperimentalSerializationApi::class)
@Suppress("EXPERIMENTAL_API_USAGE")
@Serializer(forClass = Amount::class)
internal object KotlinXAmountSerializer : KSerializer<Amount> {
    override fun serialize(encoder: Encoder, value: Amount) {
        encoder.encodeString(value.toJSONString())
    }

    override fun deserialize(decoder: Decoder): Amount {
        return Amount.fromJSONString(decoder.decodeString())
    }
}

@RequiresApi(Build.VERSION_CODES.N)
fun java.text.DecimalFormatSymbols.toIcu(targetLocale: Locale? = null): DecimalFormatSymbols {
    val targetLocale = targetLocale ?: Locale.getDefault()
    val icuSymbols = DecimalFormatSymbols(targetLocale)
    icuSymbols.zeroDigit = this.zeroDigit
    icuSymbols.groupingSeparator = this.groupingSeparator
    icuSymbols.decimalSeparator = this.decimalSeparator
    icuSymbols.perMill = this.perMill
    icuSymbols.percent = this.percent
    icuSymbols.digit = this.digit
    icuSymbols.patternSeparator = this.patternSeparator
    icuSymbols.infinity = this.infinity
    icuSymbols.naN = this.naN
    icuSymbols.minusSign = this.minusSign
    icuSymbols.currencySymbol = this.currencySymbol
    icuSymbols.internationalCurrencySymbol = this.internationalCurrencySymbol
    icuSymbols.exponentSeparator = this.exponentSeparator
    icuSymbols.monetaryDecimalSeparator = this.monetaryDecimalSeparator
    if (Build.VERSION.SDK_INT >= 34) {
        icuSymbols.monetaryGroupingSeparator = this.monetaryGroupingSeparator
    }
    return icuSymbols
}