2020-11-21 16:48:20 +00:00
|
|
|
use serde::Deserialize;
|
2020-11-22 01:31:50 +00:00
|
|
|
use serde_json::from_str;
|
2020-11-21 16:48:20 +00:00
|
|
|
use serenity::prelude::TypeMapKey;
|
2020-11-22 01:31:50 +00:00
|
|
|
|
|
|
|
use std::{collections::HashMap, error::Error, sync::Arc};
|
|
|
|
|
|
|
|
use crate::consts::LOCAL_LANGUAGE;
|
2020-11-21 16:48:20 +00:00
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct LanguageManager {
|
|
|
|
languages: HashMap<String, String>,
|
|
|
|
strings: HashMap<String, HashMap<String, String>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl LanguageManager {
|
2020-11-22 01:31:50 +00:00
|
|
|
pub fn from_compiled(content: &'static str) -> Result<Self, Box<dyn Error + Send + Sync>> {
|
|
|
|
let new: Self = from_str(content.as_ref())?;
|
2020-11-21 16:48:20 +00:00
|
|
|
|
|
|
|
Ok(new)
|
|
|
|
}
|
|
|
|
|
2020-11-22 01:31:50 +00:00
|
|
|
pub fn get(&self, language: &str, name: &str) -> &str {
|
2020-11-21 16:48:20 +00:00
|
|
|
self.strings
|
|
|
|
.get(language)
|
|
|
|
.map(|sm| sm.get(name))
|
|
|
|
.expect(&format!(r#"Language does not exist: "{}""#, language))
|
2020-11-22 01:31:50 +00:00
|
|
|
.unwrap_or_else(|| {
|
|
|
|
self.strings
|
|
|
|
.get(&*LOCAL_LANGUAGE)
|
|
|
|
.map(|sm| {
|
|
|
|
sm.get(name)
|
|
|
|
.expect(&format!(r#"String does not exist: "{}""#, name))
|
|
|
|
})
|
|
|
|
.expect("LOCAL_LANGUAGE is not available")
|
|
|
|
})
|
2020-11-21 16:48:20 +00:00
|
|
|
}
|
|
|
|
|
2020-11-22 01:31:50 +00:00
|
|
|
pub fn get_language(&self, language: &str) -> Option<&str> {
|
2020-11-22 12:09:57 +00:00
|
|
|
let language_normal = language.to_lowercase();
|
|
|
|
|
2020-11-21 16:48:20 +00:00
|
|
|
self.languages
|
|
|
|
.iter()
|
2020-11-22 12:09:57 +00:00
|
|
|
.filter(|(k, v)| {
|
|
|
|
k.to_lowercase() == language_normal || v.to_lowercase() == language_normal
|
|
|
|
})
|
2020-11-22 01:31:50 +00:00
|
|
|
.map(|(k, _)| k.as_str())
|
|
|
|
.next()
|
|
|
|
}
|
|
|
|
|
2020-11-23 14:11:57 +00:00
|
|
|
pub fn get_language_by_flag(&self, flag: &str) -> Option<&str> {
|
|
|
|
self.languages
|
|
|
|
.iter()
|
|
|
|
.filter(|(k, _)| self.get(k, "flag") == flag)
|
|
|
|
.map(|(k, _)| k.as_str())
|
|
|
|
.next()
|
|
|
|
}
|
|
|
|
|
2020-11-22 01:31:50 +00:00
|
|
|
pub fn all_languages(&self) -> impl Iterator<Item = (&str, &str)> {
|
|
|
|
self.languages.iter().map(|(k, v)| (k.as_str(), v.as_str()))
|
2020-11-21 16:48:20 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TypeMapKey for LanguageManager {
|
2020-11-22 01:31:50 +00:00
|
|
|
type Value = Arc<Self>;
|
2020-11-21 16:48:20 +00:00
|
|
|
}
|