use crate::base::{Lang, N2WError, Result};
use crate::currency::{CurrencyForms, CurrencyValue};
use crate::floatpath::FloatValue;
use crate::strnum::{python_decimal_parse, ParsedNumber};
use bigdecimal::BigDecimal;
use num_bigint::BigInt;
use num_traits::{Signed, ToPrimitive, Zero};
use std::collections::HashMap;
use std::str::FromStr;
const ONES: [&str; 10] = [
"", "kow", "laba", "saddex", "afar", "shan", "lix", "toddoba", "siddeed", "sagaal",
];
const TENS: [&str; 10] = [
"",
"toban",
"labaatan",
"soddon",
"afartan",
"konton",
"lixdan",
"toddobaatan",
"siddeetan",
"sagaashan",
];
const HUNDRED: &str = "boqol";
const THOUSAND: &str = "kun";
const MILLION: &str = "milyan";
const NEGWORD: &str = "minus ";
const ZERO_WORD: &str = "zero";
const DIGIT_FALLBACK_FLOOR: u32 = 1_000_000_000;
const LANG_NAME: &str = "Num2Word_SO";
const FALLBACK_CURRENCY: &str = "SOS";
const SEPARATOR_UNSET: &str = ",";
const SEPARATOR_DEFAULT: &str = " ";
pub struct LangSo {
forms: HashMap<&'static str, CurrencyForms>,
}
impl Default for LangSo {
fn default() -> Self {
Self::new()
}
}
impl LangSo {
pub fn new() -> Self {
let mut forms = HashMap::with_capacity(3);
forms.insert(
"SOS",
CurrencyForms::new(&["shilin", "shilin"], &["sent", "sent"]),
);
forms.insert(
"USD",
CurrencyForms::new(&["dollar", "dollars"], &["cent", "cents"]),
);
forms.insert(
"EUR",
CurrencyForms::new(&["euro", "euros"], &["cent", "cents"]),
);
LangSo { forms }
}
fn int_to_word(&self, number: &BigInt) -> String {
if number.is_zero() {
return ZERO_WORD.to_string();
}
if number.is_negative() {
return format!("{}{}", NEGWORD, self.int_to_word(&number.abs()));
}
if *number >= BigInt::from(DIGIT_FALLBACK_FLOOR) {
return number.to_string();
}
match number.to_u32() {
Some(n) => self.small_to_word(n),
None => number.to_string(),
}
}
fn small_to_word(&self, number: u32) -> String {
if number < 10 {
return ONES[number as usize].to_string();
}
if number < 100 {
let tens_val = (number / 10) as usize;
let ones_val = (number % 10) as usize;
if ones_val == 0 {
return TENS[tens_val].to_string();
}
return format!("{} {}", TENS[tens_val], ONES[ones_val]);
}
if number < 1_000 {
let hundreds_val = (number / 100) as usize;
let remainder = number % 100;
let mut result = format!("{} {}", ONES[hundreds_val], HUNDRED);
if remainder != 0 {
result.push(' ');
result.push_str(&self.small_to_word(remainder));
}
return result;
}
if number < 1_000_000 {
let thousands_val = number / 1_000;
let remainder = number % 1_000;
let mut result = format!("{} {}", self.small_to_word(thousands_val), THOUSAND);
if remainder != 0 {
result.push(' ');
result.push_str(&self.small_to_word(remainder));
}
return result;
}
let millions_val = number / 1_000_000;
let remainder = number % 1_000_000;
let mut result = format!("{} {}", self.small_to_word(millions_val), MILLION);
if remainder != 0 {
result.push(' ');
result.push_str(&self.small_to_word(remainder));
}
result
}
fn cardinal_from_str(&self, n: &str) -> Result<String> {
let n = n.trim();
let (n, ret): (&str, &str) = match n.strip_prefix('-') {
Some(rest) => (rest, NEGWORD),
None => (n, ""),
};
if let Some((left, right)) = n.split_once('.') {
let mut out = String::from(ret);
out.push_str(&self.int_to_word(&python_int(left)?));
out.push(' ');
out.push_str(self.pointword());
out.push(' ');
for ch in right.chars() {
let d = ch.to_digit(10).ok_or_else(|| {
N2WError::Value(format!(
"invalid literal for int() with base 10: '{}'",
ch
))
})?;
out.push_str(&self.int_to_word(&BigInt::from(d)));
out.push(' ');
}
Ok(out.trim().to_string())
} else {
Ok(format!("{}{}", ret, self.int_to_word(&python_int(n)?))
.trim()
.to_string())
}
}
}
impl Lang for LangSo {
fn cardinal_float_entry(
&self,
value: &crate::floatpath::FloatValue,
precision_override: Option<u32>,
) -> crate::base::Result<String> {
self.to_cardinal_float(value, precision_override)
}
fn ordinal_float_entry(&self, value: &FloatValue) -> Result<String> {
Ok(format!("{}-aad", self.cardinal_float_entry(value, None)?))
}
fn ordinal_num_float_entry(&self, _value: &FloatValue, repr_str: &str) -> Result<String> {
Ok(format!("{}.", repr_str))
}
fn str_to_number(&self, s: &str) -> Result<ParsedNumber> {
match python_decimal_parse(s)? {
ParsedNumber::Inf { .. } => Err(N2WError::Value(
"invalid literal for int() with base 10: 'Infinity'".into(),
)),
other => Ok(other),
}
}
fn default_currency(&self) -> &str {
"SOS"
}
fn default_separator(&self) -> &str {
" "
}
fn negword(&self) -> &str {
NEGWORD
}
fn pointword(&self) -> &str {
"point"
}
fn to_cardinal(&self, value: &BigInt) -> Result<String> {
let (magnitude, ret) = if value.is_negative() {
(value.abs(), NEGWORD)
} else {
(value.clone(), "")
};
Ok(format!("{}{}", ret, self.int_to_word(&magnitude))
.trim()
.to_string())
}
fn to_ordinal(&self, value: &BigInt) -> Result<String> {
Ok(format!("{}-aad", self.to_cardinal(value)?))
}
fn to_ordinal_num(&self, value: &BigInt) -> Result<String> {
Ok(format!("{}.", value))
}
fn to_year(&self, value: &BigInt) -> Result<String> {
self.to_cardinal(value)
}
fn to_cardinal_float(
&self,
value: &FloatValue,
_precision_override: Option<u32>,
) -> Result<String> {
self.cardinal_from_str(&python_str(value))
}
fn lang_name(&self) -> &str {
LANG_NAME
}
fn currency_forms(&self, code: &str) -> Option<&CurrencyForms> {
self.forms.get(code)
}
fn to_currency(
&self,
val: &CurrencyValue,
currency: &str,
cents: bool,
separator: Option<&str>,
adjective: bool,
) -> Result<String> {
let separator = separator.unwrap_or(self.default_separator());
let _ = adjective;
let separator = if separator == SEPARATOR_UNSET {
SEPARATOR_DEFAULT
} else {
separator
};
let is_negative = val.is_negative();
let s = match val {
CurrencyValue::Int(i) => if is_negative { i.abs() } else { i.clone() }.to_string(),
CurrencyValue::Decimal { value: d, .. } => if is_negative { d.abs() } else { d.clone() }.to_string(),
};
let mut parts = s.split('.');
let p0 = parts.next().unwrap_or("");
let p1 = parts.next();
let left = if p0.is_empty() {
BigInt::zero()
} else {
BigInt::from_str(p0).map_err(|_| {
N2WError::Value(format!("invalid literal for int() with base 10: '{}'", p0))
})?
};
let right = match p1 {
Some(frac) if !frac.is_empty() => {
let mut f: String = frac.chars().take(2).collect();
while f.chars().count() < 2 {
f.push('0'); }
BigInt::from_str(&f).map_err(|_| {
N2WError::Value(format!("invalid literal for int() with base 10: '{}'", f))
})?
}
_ => BigInt::zero(),
};
let forms = self.forms.get(currency).unwrap_or_else(|| {
self.forms
.get(FALLBACK_CURRENCY)
.expect("new() always inserts SOS")
});
let (cr1, cr2) = (&forms.unit, &forms.subunit);
let one = BigInt::from(1);
let mut result = format!(
"{} {}",
self.int_to_word(&left),
if left != one { &cr1[1] } else { &cr1[0] }
);
if cents && !right.is_zero() {
result.push_str(separator);
result.push_str(&format!(
"{} {}",
self.int_to_word(&right),
if right != one { &cr2[1] } else { &cr2[0] }
));
}
if is_negative {
result = format!("{}{}", NEGWORD, result);
}
Ok(result.trim().to_string())
}
}
fn python_str(v: &FloatValue) -> String {
match v {
FloatValue::Float { value, .. } => python_float_repr(*value),
FloatValue::Decimal { value, .. } => python_decimal_str(value),
}
}
fn python_int(s: &str) -> Result<BigInt> {
BigInt::from_str(s).map_err(|_| {
N2WError::Value(format!(
"invalid literal for int() with base 10: '{}'",
s
))
})
}
fn python_float_repr(v: f64) -> String {
if v.is_nan() {
return "nan".to_string();
}
if v.is_infinite() {
return (if v.is_sign_negative() { "-inf" } else { "inf" }).to_string();
}
let sign = if v.is_sign_negative() { "-" } else { "" };
let a = v.abs();
let s = format!("{:e}", a);
let (mant, exp) = s.split_once('e').expect("LowerExp always emits an 'e'");
let exp: i32 = exp.parse().expect("LowerExp emits an integer exponent");
let mut digits: String = mant.chars().filter(|c| *c != '.').collect();
let mut decpt = exp + 1;
let frac_digits = digits.chars().count() as i32 - decpt;
if frac_digits > 0 && a != 0.0 {
let t = format!("{:.*}", frac_digits as usize, a);
let (ip, fp) = t.split_once('.').expect("frac_digits > 0 forces a point");
let all = format!("{}{}", ip, fp);
let trimmed = all.trim_start_matches('0');
if !trimmed.is_empty() {
let lead = all.chars().count() - trimmed.chars().count();
digits = trimmed.to_string();
decpt = ip.chars().count() as i32 - lead as i32;
}
}
let n = digits.chars().count() as i32;
if decpt <= -4 || decpt > 16 {
let e = decpt - 1;
let mut out = String::from(sign);
let mut it = digits.chars();
out.push(it.next().expect("a finite double has at least one digit"));
if n > 1 {
out.push('.');
out.push_str(it.as_str());
}
out.push('e');
out.push(if e < 0 { '-' } else { '+' });
out.push_str(&format!("{:02}", (e as i64).abs()));
out
} else if decpt <= 0 {
format!("{}0.{}{}", sign, "0".repeat((-decpt) as usize), digits)
} else if decpt >= n {
format!("{}{}{}.0", sign, digits, "0".repeat((decpt - n) as usize))
} else {
let k = decpt as usize;
format!(
"{}{}.{}",
sign,
digits.chars().take(k).collect::<String>(),
digits.chars().skip(k).collect::<String>()
)
}
}
fn python_decimal_str(d: &BigDecimal) -> String {
let (unscaled, scale) = d.as_bigint_and_exponent();
let sign = if unscaled.is_negative() { "-" } else { "" };
let int_digits = unscaled.abs().to_string();
let exp: i64 = -scale;
let ndig = int_digits.chars().count() as i64;
let leftdigits = exp + ndig;
let dotplace = if exp <= 0 && leftdigits > -6 {
leftdigits
} else {
1
};
let (intpart, fracpart) = if dotplace <= 0 {
(
"0".to_string(),
format!(".{}{}", "0".repeat((-dotplace) as usize), int_digits),
)
} else if dotplace >= ndig {
(
format!("{}{}", int_digits, "0".repeat((dotplace - ndig) as usize)),
String::new(),
)
} else {
let k = dotplace as usize;
(
int_digits.chars().take(k).collect::<String>(),
format!(".{}", int_digits.chars().skip(k).collect::<String>()),
)
};
let exp_part = if leftdigits == dotplace {
String::new()
} else {
format!("E{:+}", leftdigits - dotplace)
};
format!("{}{}{}{}", sign, intpart, fracpart, exp_part)
}