money-module/src/main/kotlin/com/cubetiqs/libra/moneyutils/MoneyConfig.kt

55 lines
1.6 KiB
Kotlin
Raw Normal View History

2020-08-26 20:06:06 +07:00
package com.cubetiqs.libra.moneyutils
/**
* Default money config in static object.
*
* @author sombochea
* @since 1.0
*/
object MoneyConfig {
private const val SPLIT_ORD_1 = ','
private const val SPLIT_ORD_2 = '='
/**
2020-08-26 20:19:06 +07:00
* All money currencies and its rate are stored in memory state for exchange or compute the value.
*
2020-08-26 20:06:06 +07:00
* Key is the currency
* Value is the rate
*/
2020-08-26 20:19:06 +07:00
private val config: MutableMap<String, Double> = mutableMapOf()
2020-08-26 20:06:06 +07:00
2020-08-26 20:19:06 +07:00
/**
* Parse the config string to currency's map within rates
* Key is money's currency (String)
* Value is money's value (Double)
*/
fun parse(config: String, clearAllStates: Boolean = true) {
if (clearAllStates) {
this.config.clear()
}
2020-08-26 20:06:06 +07:00
val rates = config.split(SPLIT_ORD_1)
rates.map { i ->
val temp = i.split(SPLIT_ORD_2)
if (temp.size == 2) {
2020-08-26 20:19:06 +07:00
val currency = temp[0].toUpperCase()
2020-08-26 20:06:06 +07:00
val value = temp[1].toDouble()
2020-08-26 20:19:06 +07:00
if (this.config.containsKey(currency)) {
this.config.replace(currency, value)
} else {
this.config.put(currency, value)
}
2020-08-26 20:06:06 +07:00
} else {
2020-08-26 20:19:06 +07:00
throw MoneyCurrencyStateException("money config format is not valid!")
2020-08-26 20:06:06 +07:00
}
}
}
// all currencies with its rate
fun getConfig() = this.config
2020-08-26 20:19:06 +07:00
@Throws(MoneyCurrencyStateException::class)
2020-08-26 20:06:06 +07:00
fun getRate(currency: String): Double {
2020-08-26 20:19:06 +07:00
return getConfig()[currency.toUpperCase()]
?: throw MoneyCurrencyStateException("money currency $currency is not valid!")
2020-08-26 20:06:06 +07:00
}
}