1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
use crate::{
    app::AppBuilder,
    assets::{
        asset::AssetId, database::AssetsDatabase, protocols::localization::LocalizationAsset,
    },
    ecs::{
        pipeline::{PipelineBuilder, PipelineBuilderError},
        Universe,
    },
};
use pest::{iterators::Pair, Parser};
use std::{collections::HashMap, fmt::Write};

#[allow(clippy::upper_case_acronyms)]
mod parser {
    #[derive(Parser)]
    #[grammar = "localization.pest"]
    pub(super) struct SentenceParser;
}

#[derive(Default)]
pub struct Localization {
    default_language: Option<String>,
    current_language: Option<String>,
    /// { text id: { language: text format } }
    map: HashMap<String, HashMap<String, String>>,
}

impl Localization {
    pub fn default_language(&self) -> Option<&str> {
        self.default_language.as_deref()
    }

    pub fn set_default_language(&mut self, value: Option<String>) {
        self.default_language = value;
    }

    pub fn current_language(&self) -> Option<&str> {
        self.current_language.as_deref()
    }

    pub fn set_current_language(&mut self, value: Option<String>) {
        self.current_language = value.clone();
        if self.default_language.is_none() && value.is_some() {
            self.default_language = value;
        }
    }

    pub fn add_text(&mut self, id: &str, language: &str, text_format: &str) {
        if let Some(map) = self.map.get_mut(id) {
            map.insert(language.to_owned(), text_format.to_owned());
        } else {
            let mut map = HashMap::new();
            map.insert(language.to_owned(), text_format.to_owned());
            self.map.insert(id.to_owned(), map);
        }
    }

    pub fn remove_text(&mut self, id: &str, language: &str) -> bool {
        let (empty, removed) = if let Some(map) = self.map.get_mut(id) {
            let removed = map.remove(language).is_some();
            let empty = map.is_empty();
            (empty, removed)
        } else {
            (false, false)
        };
        if empty {
            self.map.remove(id);
        }
        removed
    }

    pub fn remove_text_all(&mut self, id: &str) -> bool {
        self.map.remove(id).is_some()
    }

    pub fn remove_language(&mut self, lang: &str) {
        for map in self.map.values_mut() {
            map.remove(lang);
        }
    }

    pub fn find_text_format(&self, id: &str) -> Option<&str> {
        if let Some(current) = &self.current_language {
            if let Some(default) = &self.default_language {
                if let Some(map) = self.map.get(id) {
                    return map
                        .get(current)
                        .or_else(|| map.get(default))
                        .or(None)
                        .as_ref()
                        .map(|v| v.as_str());
                }
            }
        }
        None
    }

    pub fn format_text(&self, id: &str, params: &[(&str, &str)]) -> Result<String, String> {
        if let Some(text_format) = self.find_text_format(id) {
            match parser::SentenceParser::parse(parser::Rule::sentence, text_format) {
                Ok(mut ast) => {
                    let pair = ast.next().unwrap();
                    match pair.as_rule() {
                        parser::Rule::sentence => Ok(Self::parse_sentence_inner(pair, params)),
                        _ => unreachable!(),
                    }
                }
                Err(error) => Err(error.to_string()),
            }
        } else {
            Err(format!("There is no text format for id: {}", id))
        }
    }

    fn parse_sentence_inner(pair: Pair<parser::Rule>, params: &[(&str, &str)]) -> String {
        let mut result = String::new();
        for p in pair.into_inner() {
            match p.as_rule() {
                parser::Rule::text => result.push_str(&p.as_str().replace("\\|", "|")),
                parser::Rule::identifier => {
                    let ident = p.as_str();
                    if let Some((_, v)) = params.iter().find(|(id, _)| id == &ident) {
                        result.push_str(v);
                    } else {
                        write!(result, "{{@{}}}", ident).unwrap();
                    }
                }
                _ => {}
            }
        }
        result
    }
}

#[macro_export]
macro_rules! localization_format_text {
    ($res:expr, $text:expr, $( $id:ident => $value:expr ),*) => {
        $crate::localization::Localization::format_text(
            &$res,
            $text,
            &[ $( (stringify!($id), &$value.to_string()) ),* ]
        )
    }
}

#[derive(Default)]
pub struct LocalizationSystemCache {
    language_table: HashMap<AssetId, String>,
}

pub type LocalizationSystemResources<'a> = (
    &'a AssetsDatabase,
    &'a mut Localization,
    &'a mut LocalizationSystemCache,
);

pub fn localization_system(universe: &mut Universe) {
    let (assets, mut localization, mut cache) =
        universe.query_resources::<LocalizationSystemResources>();

    for id in assets.lately_loaded_protocol("locals") {
        let id = *id;
        let asset = assets
            .asset_by_id(id)
            .expect("trying to use not loaded localization asset");
        let asset = asset
            .get::<LocalizationAsset>()
            .expect("trying to use non-localization asset");
        for (k, v) in &asset.dictionary {
            localization.add_text(k, &asset.language, v);
        }
        cache.language_table.insert(id, asset.language.clone());
    }
    for id in assets.lately_unloaded_protocol("locals") {
        if let Some(name) = cache.language_table.remove(id) {
            localization.remove_language(&name);
        }
    }
}

pub fn bundle_installer<PB, PMS>(
    builder: &mut AppBuilder<PB>,
    _: (),
) -> Result<(), PipelineBuilderError>
where
    PB: PipelineBuilder,
{
    builder.install_resource(Localization::default());
    builder.install_resource(LocalizationSystemCache::default());
    builder.install_system::<LocalizationSystemResources>(
        "localization",
        localization_system,
        &[],
    )?;
    Ok(())
}