use std::collections::HashMap;
use crate::Lingo;
use crate::locales::Locale;
pub type InternationalString = HashMap<Locale, &'static str>;
pub type LingoStrings = HashMap<&'static str, InternationalString>;
pub fn get_localised_string(string: &InternationalString, locale: &Locale) -> Option<String> {
match string.get(&locale) {
Some(x) => return Some(x.to_string()),
None => {}
}
for (locale1, string) in string.iter() {
if locale1.language() == locale.language() {
return Some(string.to_string());
}
}
None
}
impl Lingo {
pub fn get_international_string(&self, id: &str) -> Option<InternationalString> {
let international_string: Option<&InternationalString> = self.strings().get(id);
match international_string {
Some(x) => Some(x.clone()),
None => None,
}
}
pub fn string(&self, id: &str) -> Option<String> {
let international_string: Option<InternationalString> = self.get_international_string(id);
if international_string == None {
return None;
}
let international_string = international_string.unwrap();
let localised_string: Option<String> =
get_localised_string(&international_string, self.context_locale());
if localised_string != None {
return localised_string;
}
get_localised_string(&international_string, &self.default_locale())
}
}
#[cfg(test)]
mod tests {
use crate::locales::{
countries::CountryCode,
languages::{Language, LanguageCode},
};
use super::*;
#[test]
fn app() {
let ar = Locale(Language::new(LanguageCode::ar), CountryCode::None);
let fr = Locale(Language::new(LanguageCode::fr), CountryCode::None);
let en = Locale(Language::new(LanguageCode::en), CountryCode::None);
#[allow(non_snake_case)]
let en_GB = Locale(Language::new(LanguageCode::en), CountryCode::GB);
let de = Locale(Language::new(LanguageCode::de), CountryCode::None);
let lingo_strings: LingoStrings = HashMap::from([(
"hello_world",
HashMap::from([
(fr, "Bonjour le monde !"),
(en_GB, "Hello world!"),
(de, "Hallo Welt!"),
]),
)]);
let lingo = Lingo::new(ar, en, lingo_strings);
println!("{}", lingo.string("hello_world").unwrap());
}
#[test]
fn from_system_locale() {
let fr = Locale(Language::new(LanguageCode::fr), CountryCode::None);
let en = Locale(Language::new(LanguageCode::en), CountryCode::None);
#[allow(non_snake_case)]
let en_GB = Locale(Language::new(LanguageCode::en), CountryCode::GB);
let de = Locale(Language::new(LanguageCode::de), CountryCode::None);
let lingo_strings: LingoStrings = HashMap::from([(
"hello_world",
HashMap::from([
(fr.clone(), "Bonjour le monde !"),
(en_GB, "Hello world!"),
(de, "Hallo Welt!"),
]),
)]);
let lingo = Lingo::with_system_context_locale(fr, lingo_strings);
println!("{}", lingo.string("hello_world").unwrap());
}
}