use crate::tina::i18n::ResourceBundle;
use std::fmt::Display;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct I18nString {
direct: bool,
key: String,
args: Vec<(String, String)>,
}
impl I18nString {
pub fn from_key(key: impl Display) -> I18nString {
I18nString {
direct: false,
key: format!("{}", key),
args: vec![],
}
}
pub fn from_key_args(key: impl Display, args: Vec<impl Display>) -> I18nString {
let mut new_args: Vec<(String, String)> = Vec::with_capacity(args.len());
let mut idx = -1;
for arg in args.into_iter() {
idx += 1;
new_args.push((idx.to_string(), format!("{}", arg)));
}
I18nString {
direct: false,
key: format!("{}", key),
args: new_args,
}
}
pub fn from(key: impl Display, args: Vec<(impl Display, impl Display)>) -> I18nString {
I18nString {
direct: false,
key: format!("{}", key),
args: args.into_iter().map(|(key, value)| (format!("{}", key), format!("{}", value))).collect(),
}
}
pub fn direct_from(str: impl Display) -> I18nString {
I18nString {
direct: true,
key: format!("{}", str),
args: vec![],
}
}
pub fn direct_from_string(str: String) -> I18nString {
I18nString {
direct: true,
key: str,
args: vec![],
}
}
pub fn add_arg(&mut self, name: impl Display, value: impl Display) -> &mut Self {
self.args.push((format!("{}", name), format!("{}", value)));
self
}
pub fn get_string(&self, locale: &str) -> String {
if self.direct {
return self.key.to_string();
}
ResourceBundle::get_string_by_key_args(
locale,
&self.key,
self.args.iter().map(|(key, value)| (key.as_str(), value.as_str())).collect(),
)
}
}
impl PartialEq for I18nString {
fn eq(&self, other: &Self) -> bool {
let locale = ResourceBundle::get_default_locale();
self.get_string(locale.as_str()) == other.get_string(locale.as_str())
}
}