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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//!
//! [!["ay that's where the 'stralian accent comes through"](https://raw.githubusercontent.com/BuyMyMojo/rust_nickname_generater/master/images/TheReasonTheNameIsSpeltLikeThatOhMyThisIsALongFileName.png)](https://s3.buymymojo.net/ShareX/2022/08/01/17/rust%20nickname%20genera.wav)
//!
//! > Yes I am australian :)
//!
//! This is a super simple lib I made for practice.
//!
//! The usernames generated are based on the names we all have in the [Serenity/Poise discord](https://discord.gg/serenity-rs) and the [rust community discord](https://discord.gg/rust-lang-communit)
//!
//! ## Basic use:
//! ```rust
//! use rust_nickname_generater::generate_random_name;
//!
//! // Generate a name that will fit in Discord
//! println!("{}", generate_random_name("mojo".to_string(), 32).unwrap());
//! ```

use new_string_template::template::Template;
use once_cell::sync::Lazy;
use rand::seq::SliceRandom;
use regex::Regex;
use std::{collections::HashMap, ops::Add};

pub mod error;
pub mod template_struct;
pub mod templates;

use crate::error::{Error, Result};

use crate::template_struct::{NameTemplate, NameType};
use crate::templates::{
    FUNCTION_TEMPLTES, FUNCTION_VARIABLE_TEMPLTES, MACRO_TEMPLTES, VARIABLE_TEMPLTES,
};

// ? I don't think I need to make this public?
// The following regex requires at least one space between "{{" and "}}" and allows variables with spaces
static STRING_TEMPLATE_MATCHER: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?mi)\{\{\s+([^\}]+)\s+\}\}").unwrap());

/// Given a username and `NameTemplate` output the rendered name
///
/// ```rust
/// use rust_nickname_generater::template_struct::*;
/// use rust_nickname_generater::{generate_name, get_template_by_name};
///
/// // Search for specific template by name
/// let template: Option<NameTemplate> = get_template_by_name("Deny warnings");
///
/// let nickname = generate_name("Mojo".to_string(), template.unwrap()).unwrap();
///
///  assert_eq!(nickname, "#![deny(warnings)] Mojo();")
///
/// ```
///
/// # Errors
///
/// Will return an error if for some reason [`new_string_template`](https://lib.rs/new_string_template) fails to render the template.
/// It will be an `Error::UsernameLenConversionFailed`
pub fn generate_name(username: String, template: NameTemplate) -> Result<String> {
    let templ = Template::new(template.contents).with_regex(&STRING_TEMPLATE_MATCHER);
    let data = {
        let mut map = HashMap::new();
        map.insert("username", username);
        map
    };

    match templ.render(&data) {
        Ok(s) => Ok(s),
        Err(e) => Err(e.into()),
    }
}

/// Generate a random name that fits within a specified character limit
///
/// ```rust
/// use rust_nickname_generater::generate_random_name;
///
/// // Generate a name that will fit in Discord
/// println!("{}", generate_random_name("mojo".to_string(), 32).unwrap());
/// ```
///
/// # Errors
///
/// This can only fail if it fails to convert the username.len() to a u64 for length check.
/// If this does happen to occur it will return `Error::UsernameLenConversionFailed`.
pub fn generate_random_name(username: String, char_limit: u64) -> Result<String> {
    let name_len: u64 = match username.len().try_into() {
        Ok(x) => x,
        Err(e) => return Err(e.into()),
    };
    // Make sure name isn't too long/limit is too small
    if char_limit < name_len {
        return Err(Error::LengthLimit);
    }

    let all_templates = get_all_templates();
    let mut valid_templates: Vec<NameTemplate> = Vec::new();

    for temp in all_templates {
        let total_len: u64 = temp.info.len.add(username.len() as u64);

        // Only push templates that can possibly fit within limit after being rendered
        if total_len.le(&char_limit) {
            valid_templates.push(temp);
        }
    }

    // Error if the name is too large
    if valid_templates.is_empty() {
        return Err(Error::NoValidName);
    }

    let template = match valid_templates.choose(&mut rand::thread_rng()) {
        Some(t) => t,
        None => unreachable!(),
    };

    generate_name(username, *template)
}

/// Returns a Vec<String> of all template names
#[must_use]
pub fn get_all_template_names() -> Vec<String> {
    let templates = get_all_templates();

    let mut names: Vec<String> = Vec::new();

    for temp in templates {
        names.push(temp.name.to_string());
    }

    names.sort();

    names
}

/// Returns a Vec<String> of all template examples
#[must_use]
pub fn get_all_template_examples() -> Vec<String> {
    let templates = get_all_templates();

    let mut examples: Vec<String> = Vec::new();

    for temp in templates {
        examples.push(temp.example.to_string());
    }

    examples.sort();

    examples
}

// TODO: Add fuzzy search?
/// Returns an option with a template with the given name
#[must_use]
pub fn get_template_by_name(name: &str) -> Option<NameTemplate<'static>> {
    let templates = get_all_templates();

    // Search for specific template by name
    templates.into_iter().find(|x| *x.name == *name)
}

/// Returns a Vec of all built in templates
///
/// ```rust
/// use rust_nickname_generater::get_all_templates;
/// use rust_nickname_generater::template_struct::NameTemplate;
///
/// let templates: Vec<NameTemplate> = get_all_templates();
///
/// println!("{:?}", templates.first());
/// ```
#[must_use]
pub fn get_all_templates() -> Vec<NameTemplate<'static>> {
    let mut templates: Vec<NameTemplate> = Vec::new();

    for temp in FUNCTION_TEMPLTES {
        templates.push(temp);
    }

    for temp in VARIABLE_TEMPLTES {
        templates.push(temp);
    }

    for temp in FUNCTION_VARIABLE_TEMPLTES {
        templates.push(temp);
    }

    for temp in MACRO_TEMPLTES {
        templates.push(temp);
    }

    templates
}

/// Returns a Vec of templates matching specified type
///
/// ```rust
/// use rust_nickname_generater::get_templates_of_type;
/// use rust_nickname_generater::template_struct::{NameType, NameTemplate};
///
/// let templates: Vec<NameTemplate> = get_templates_of_type(NameType::Function);
///
/// println!("{:?}", templates.first());
/// ```
#[must_use]
pub fn get_templates_of_type(name_type: NameType) -> Vec<NameTemplate<'static>> {
    let mut templates: Vec<NameTemplate> = Vec::new();

    match name_type {
        NameType::Macro => {
            let con = MACRO_TEMPLTES;

            for temp in con {
                templates.push(temp);
            }
        }
        NameType::Var => {
            let con = VARIABLE_TEMPLTES;

            for temp in con {
                templates.push(temp);
            }
        }
        NameType::FunctionVar => {
            let con = FUNCTION_VARIABLE_TEMPLTES;

            for temp in con {
                templates.push(temp);
            }
        }
        NameType::Function => {
            let con = FUNCTION_TEMPLTES;

            for temp in con {
                templates.push(temp);
            }
        }
    }

    templates
}

#[cfg(test)]
mod tests {
    use super::error::Error;
    use super::*;

    #[test]
    fn function_template() {
        let templates = get_templates_of_type(NameType::Function);
        let temp = templates.first().unwrap();
        let result = generate_name("yuna".to_string(), *temp).unwrap();
        assert_eq!(result, "#![deny(warnings)] yuna();".to_string());
    }

    #[test]
    fn var_template() {
        let templates = get_templates_of_type(NameType::Var);
        let temp = templates.first().unwrap();
        let result = generate_name("evelyn".to_string(), *temp).unwrap();
        assert_eq!(result, "&'a evelyn".to_string());
    }

    #[test]
    fn func_var_template() {
        let templates = get_templates_of_type(NameType::FunctionVar);
        let temp = templates.first().unwrap();
        let result = generate_name("BuyMyMojo".to_string(), *temp).unwrap();
        assert_eq!(result, r#"Some("BuyMyMojo");"#.to_string());
    }

    #[test]
    fn macro_template() {
        let templates = get_templates_of_type(NameType::Macro);
        let temp = templates.first().unwrap();
        let result = generate_name("mojo".to_string(), *temp).unwrap();
        assert_eq!(result, "#![allow(mojo)]".to_string());
    }

    #[test]
    fn too_small_line_limite() {
        let result = generate_random_name("mojo".to_string(), 1);
        assert_eq!(result.err(), Some(Error::LengthLimit));
    }

    #[test]
    fn no_valid_template() {
        let result =
            generate_random_name("ThisNameWon'tHaveAValidUsernameTemplate".to_string(), 39);
        assert_eq!(result.err(), Some(Error::NoValidName));
    }

    #[test]
    fn random_name() {
        let result = generate_random_name("mojo".to_string(), 32);
        assert!(result.is_ok());
    }

    #[test]
    fn list_add_examples() {
        let result = get_all_template_examples();
        println!("{:#?}", result);
        assert!(!result.is_empty());
    }

    #[test]
    fn test_all_templates() {
        let result = get_all_template_names();
        let mut fails = Vec::new();

        for name in result {
            let temp = get_template_by_name(&name).unwrap();

            match generate_name("username".to_string(), temp) {
                Ok(n) => match n.as_str() {
                    "#![deny(warnings)] username();" => {
                        println!("#![deny(warnings)] yuna();");
                    }
                    "&'a username" => {
                        println!("&'a evelyn");
                    }
                    n => {
                        println!("{n}");
                    }
                },
                Err(e) => fails.push(e),
            }
        }

        assert!(fails.is_empty());
    }

    #[test]
    fn search_for_specific_template() {
        // Search for specific template by name
        let template: Option<NameTemplate> = get_template_by_name("Deny warnings");

        let nickname = generate_name("Mojo".to_string(), template.unwrap()).unwrap();

        assert_eq!(nickname, "#![deny(warnings)] Mojo();");
    }
}