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
use std::{collections::HashMap, env};

use include_dir::{include_dir, Dir};
use lazy_static::lazy_static;
use regex::Regex;

lazy_static! {
    static ref TRANSLATIONS_HASHMAP: HashMap<&'static str, HashMap<&'static str, &'static str>> = {
        let mut all_translations: HashMap<&'static str, HashMap<&'static str, &'static str>> = HashMap::new();

        // Read all files and add them to the hashmap:
        static LOCALIZATION_DIR__: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/localization");
        for file in LOCALIZATION_DIR__.files() {
            let translation: HashMap<&'static str, &'static str> = create_translation_hashmap(file.contents_utf8().unwrap());

            all_translations.insert(file.path().file_name().unwrap().to_str().unwrap(), translation);
        }

        all_translations
    };
}


fn create_translation_hashmap( localization_string: &str ) -> HashMap<&str, &str> {
    let mut translations: HashMap<&str, &str> = HashMap::new();

    let one_line = Regex::new(r#""([\w\W]+?)"\s*=>\s*"([\w\W]+?)""#).unwrap();
    let multi_line = Regex::new(r#"\#"([\w\W]+?)"\#\s*=>\s*\#"([\w\W]+?)"\#"#).unwrap();

    // One line
    for cap in one_line.captures_iter(localization_string) {
        if let (Some(key), Some(value)) = (cap.get(1), cap.get(2)) {
            translations.insert(key.as_str(), value.as_str());
        }
    }

    // Multi Line
    for cap in multi_line.captures_iter(localization_string) {
        if let (Some(key), Some(value)) = (cap.get(1), cap.get(2)) {
            translations.insert(key.as_str(), value.as_str());
        }
    }

    translations
}

/// Get translation of the `text` in a spesific language
/// If translation exists returns the translation
/// else returns the `text` back.
/// ```rust,ignore
/// use simple_localization::trl;
/// 
/// // localization/tr_TR file exists
/// let text:&str = trl("Hello", "tr_TR"); // "Merhaba"
/// 
/// // localization/ar_QA file exists
/// let text:&str = trl("Hello", "ar_QA"); // "مرحبًا"
/// 
/// // localization/tr_TR file doesn't exists
/// let text:&str = trl("Hello", "tr_TR"); // "Hello"
/// ```
/// 
pub fn trl<'a, 'b>(text: &'a str, lang: &'b str) -> &'a str {
    match TRANSLATIONS_HASHMAP.get(lang) {
        Some(language_translations) => {
            match language_translations.get(text) {
                Some(&value) => value,
                None => {
                    eprintln!("Translation Error: No translation of '{text}' exists in '{lang}' language");
                    return text;
                }
            }
        }
        None => {
            eprintln!("Translation Error: localization/{lang} doesn't exist");
            return text;
        }
    }
}

/// Get translation of the `text` in system's language(`env::var("LANG")`)
/// If translation exists returns the translation
/// else returns the `text` back.
/// ```rust,ignore
/// use simple_localization::tr;
/// 
/// // localization/tr_TR file exists and `LANG=tr_TR.UTF-8`
/// let text:&str = tr("Hello"); // "Merhaba"
/// 
/// // localization/tr_TR file doesn't exists and `LANG=tr_TR.UTF-8`
/// let text:&str = tr("Hello"); // "Hello"
/// 
/// // localization/tr_TR file exists and `LANG=ar_QA.UTF-8`
/// let text:&str = tr("Hello"); // "Hello"
/// ```
/// 
pub fn tr(text: &str) -> &str {
    let lang = match env::var("LANG") {
        Ok(l) => l, // this returns "en_US.UTF-8"
        Err(_) => {
            eprintln!("Translation Error: 'LANG' environment variable doesn't exist");
            return text;
        }
    };

    let lang_vec:Vec<&str> = lang.split(".").collect();
    let lang_str:&str = match lang_vec.first() {
        Some(&l) => l, // this returns "en_US"
        None => {
            eprintln!("Translation Error: 'LANG' environment variable is not suitable to parse: {lang} (example: en_US.UTF-8)");
            return text;
        }
    };

    println!("LANG is: {lang_str}");

    trl(text, lang_str)
}


#[cfg(test)]
mod tr_tests {
    use super::*;

    #[test]
    fn single_word() {
        assert_eq!(tr("Hello"), "Merhaba");
    }

    

    #[test]
    fn long_sentence() {
        assert_eq!(tr("How are you?"), "Nasılsın?");
        assert_eq!(tr("This is a long text"), "Bu uzun bir yazı");
    }

    #[test]
    fn multi_line() {
        assert_eq!(
            tr(r#"This is a multiline text.

You can write anything you want here.

Don't need to use \n.

The translation of this is next the quoted text."#),
r#"Bu bir çok satırlı yazı.

Buraya istediğin her şeyi yazabilirsin.

\n kullanman gerekmez.

Bu yazının çevirisi bir sonraki tırnak içindeki yazıdır."#
        );
    }    
}

#[cfg(test)]
mod trl_tests {
    use super::*;

    #[test]
    fn single_word() {
        assert_eq!(trl("Hello", "tr_TR"), "Merhaba");
    }

    

    #[test]
    fn long_sentence() {
        assert_eq!(trl("How are you?", "tr_TR"), "Nasılsın?");
        assert_eq!(trl("This is a long text", "tr_TR"), "Bu uzun bir yazı");
    }

    #[test]
    fn multi_line() {
        assert_eq!(
            trl(r#"This is a multiline text.

You can write anything you want here.

Don't need to use \n.

The translation of this is next the quoted text."#, "tr_TR"),
r#"Bu bir çok satırlı yazı.

Buraya istediğin her şeyi yazabilirsin.

\n kullanman gerekmez.

Bu yazının çevirisi bir sonraki tırnak içindeki yazıdır."#
        );
    }    
}