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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/// Transformers for the template
use std::ops::{Bound, RangeBounds};

use crate::errors::TransformerError;
use crate::VAR_TRANSFORM_SEP_CHAR;
use lazy_static::lazy_static;
use regex::Regex;
use titlecase::titlecase;

/// Applies any tranformations to the variable, you can chain the
/// transformers called whenever you use [`VAR_TRANSFORM_SEP_CHAR`] to
/// provide a transformer in the template.
pub fn apply_tranformers(val: &str, transformations: &str) -> Result<String, TransformerError> {
    let mut val: String = val.to_string();
    for tstr in transformations.split(VAR_TRANSFORM_SEP_CHAR) {
        if tstr.is_empty() {
            continue;
        }
        let (name, args) = tstr.split_once('(').ok_or(TransformerError::InvalidSyntax(
            tstr.to_string(),
            "No opening paranthesis".to_string(),
        ))?;
        let args: Vec<&str> = args
            .strip_suffix(')')
            .ok_or(TransformerError::InvalidSyntax(
                tstr.to_string(),
                "No closing paranthesis".to_string(),
            ))?
            .split(',')
            .collect();
        val = match name {
            "f" => float_format(&val, args)?,
            "case" => string_case(&val, args)?,
            "calc" => calc(&val, args)?,
            "count" => count(&val, args)?,
            "repl" => replace(&val, args)?,
            "take" => take(&val, args)?,
            "trim" => trim(&val, args)?,
            "comma" => comma(&val, args)?,
            "group" => group(&val, args)?,
            "q" => quote(&val, args)?,
            _ => {
                return Err(TransformerError::UnknownTranformer(
                    name.to_string(),
                    val.to_string(),
                ))
            }
        };
    }
    Ok(val)
}

/// Gets the bound of a rust range object
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// # use std::ops::RangeBounds;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(bound((2..).end_bound(), true), None);
///     assert_eq!(bound((..2).end_bound(), false), Some(1));
///     assert_eq!(bound((..=2).end_bound(), false), Some(2));
///     assert_eq!(bound((..2).start_bound(), true), None);
///     assert_eq!(bound((0..).start_bound(), false), Some(0));
/// # Ok(())
/// # }
pub fn bound(b: Bound<&usize>, lower: bool) -> Option<usize> {
    match b {
        Bound::Unbounded => None,
        Bound::Included(v) => Some(*v),
        Bound::Excluded(v) => Some(if lower { v + 1 } else { v - 1 }),
    }
}

/// Checks whether the arguments lenth matches what is required
fn check_arguments_len<R: RangeBounds<usize>>(
    func_name: &'static str,
    req: R,
    given: usize,
) -> Result<(), TransformerError> {
    if req.contains(&given) {
        Ok(())
    } else {
        match (
            bound(req.start_bound(), true),
            bound(req.end_bound(), false),
        ) {
            (None, Some(r)) => Err(TransformerError::TooManyArguments(func_name, r, given)),
            (Some(r), None) => Err(TransformerError::TooFewArguments(func_name, r, given)),
            (Some(r1), Some(r2)) => {
                if given < r1 {
                    Err(TransformerError::TooFewArguments(func_name, r1, given))
                } else {
                    Err(TransformerError::TooManyArguments(func_name, r2, given))
                }
            }
            _ => Ok(()),
        }
    }
}

/// format the float (numbers). For example with `val=1.123`, `{val:f(2)}` or `{val:f(.2)}` gives `1.12`
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(float_format("1.12", vec![".1"])?, "1.1");
///     assert_eq!(float_format("1.12", vec!["2"])?, "1.12");
///     assert_eq!(float_format("1.12", vec!["0"])?, "1");
/// # Ok(())
/// # }
pub fn float_format(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "f";
    check_arguments_len(func_name, 1..=1, args.len())?;
    let format = args[0];
    let val = val
        .parse::<f64>()
        .map_err(|_| TransformerError::InvalidValueType(func_name, "float"))?;
    let mut start = 0usize;
    let mut decimal = 6usize;
    if let Some((d, f)) = format.split_once('.') {
        if !d.is_empty() {
            start = d.parse().map_err(|_| {
                TransformerError::InvalidArgumentType(func_name, d.to_string(), "uint")
            })?;
        }
        if f.is_empty() {
            decimal = 0;
        } else {
            decimal = f.parse().map_err(|_| {
                TransformerError::InvalidArgumentType(func_name, f.to_string(), "uint")
            })?;
        }
    } else if !format.is_empty() {
        decimal = format.parse().map_err(|_| {
            TransformerError::InvalidArgumentType(func_name, format.to_string(), "uint")
        })?;
    }
    Ok(format!("{0:1$.2$}", val, start, decimal))
}

/// Format the string. Supports `up`=> UPCASE, `down`=> downcase, `proper` => first character UPCASE all others downcase, `title` => title case according to [`titlecase::titlecase`]. e.g. `{var:case(up)}`.
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(string_case("na", vec!["up"])?, "NA");
///     assert_eq!(string_case("nA", vec!["down"])?, "na");
///     assert_eq!(string_case("nA", vec!["proper"])?, "Na");
///     assert_eq!(string_case("here, an apple", vec!["title"])?, "Here, an Apple");
/// # Ok(())
/// # }
pub fn string_case(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "case";
    check_arguments_len(func_name, 1..=1, args.len())?;
    let format = args[0];
    match format.to_lowercase().as_str() {
        "up" => Ok(val.to_uppercase()),
        "down" => Ok(val.to_lowercase()),
        "title" => Ok(titlecase(val)),
        "proper" => Ok({
            let mut c = val.chars();
            match c.next() {
                None => String::new(),
                Some(f) => {
                    f.to_uppercase().collect::<String>() + c.as_str().to_lowercase().as_str()
                }
            }
        }),
        _ => Err(TransformerError::InvalidArgumentType(
            func_name,
            format.to_string(),
            "{up;down;proper;title}",
        )),
    }
}

lazy_static! {
    static ref CALC_NUMBERS: Regex = Regex::new("[0-9.]+").unwrap();
}

/// Airthmatic calculations, the value needs to be float. e.g. `{val:calc(+1)}` will add 1 to the value. The order of calculation is left to right.
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(calc("1.24", vec!["+1"])?, "2.24");
///     assert_eq!(calc("1", vec!["+1*2^2"])?, "16");
///     assert_eq!(calc("1.24", vec!["+1", "-1"])?, "2.24,0.24");
/// # Ok(())
/// # }
pub fn calc(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "calc";
    check_arguments_len(func_name, 1.., args.len())?;

    let val: f64 = val
        .parse()
        .map_err(|_| TransformerError::InvalidValueType(func_name, "float"))?;
    let mut results: Vec<String> = Vec::new();
    for expr in args {
        let mut last_match = 0usize;
        let mut result = val;
        for cap in CALC_NUMBERS.captures_iter(expr) {
            let m = cap.get(0).unwrap();
            let curr_val = m.as_str().parse().map_err(|_| {
                TransformerError::InvalidArgumentType(func_name, m.as_str().to_string(), "float")
            })?;
            if m.start() == 0 {
                result = curr_val;
            } else {
                match &expr[last_match..m.start()] {
                    "+" => result += curr_val,
                    "-" => result -= curr_val,
                    "/" => result /= curr_val,
                    "*" => result *= curr_val,
                    "^" => result = result.powf(curr_val),
                    s => {
                        return Err(TransformerError::InvalidArgumentType(
                            func_name,
                            s.to_string(),
                            "{+,-,*,/,^}",
                        ))
                    }
                };
            }
            last_match = m.end();
        }
        results.push(result.to_string());
    }
    Ok(results.join(","))
}

/// Count the number of occurances of a pattern in the string. You can chain it with [`calc`] to get the number of word like: `{val:count( ):calc(+1)}`
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(count("nata", vec!["a"])?, "2");
///     assert_eq!(count("nata", vec!["a", "t"])?, "2,1");
///     assert_eq!(count("nata", vec![" "])?, "0");
///     assert_eq!(count("hi there fellow", vec![" "])?, "2");
/// # Ok(())
/// # }
pub fn count(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "count";
    check_arguments_len(func_name, 1.., args.len())?;
    let counts: Vec<String> = args
        .iter()
        .map(|sep| val.matches(sep).count().to_string())
        .collect();
    Ok(counts.join(","))
}

/// Replace text in the string, by another text
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(replace("nata", vec!["a", "o"])?, "noto");
///     assert_eq!(replace("hi there fellow", vec![" ", "-"])?, "hi-there-fellow");
/// # Ok(())
/// # }
pub fn replace(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "replace";
    check_arguments_len(func_name, 2..=2, args.len())?;
    Ok(val.replace(args[0], args[1]))
}

/// Split the text with given separator and then take the Nth group
///
/// N=0, will give the whole group separated by comma, but it might
/// give unexpected results if there is already comma in string and
/// you're splitting with something else
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(take("nata", vec!["a", "2"])?, "t");
///     assert_eq!(take("hi there fellow", vec![" ", "2"])?, "there");
///     assert_eq!(take("hi there fellow", vec![" ", "2", "2"])?, "there fellow");
/// # Ok(())
/// # }
pub fn take(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "take";
    check_arguments_len(func_name, 2..=3, args.len())?;
    let n: usize = args[1].parse().map_err(|_| {
        TransformerError::InvalidArgumentType(func_name, args[1].to_string(), "uint")
    })?;
    let spl = if args.len() == 2 {
        val.split(args[0]).nth(n - 1)
    } else {
        val.splitn(
            args[2].parse().map_err(|_| {
                TransformerError::InvalidArgumentType(func_name, args[1].to_string(), "int")
            })?,
            args[0],
        )
        .nth(n - 1)
    };

    Ok(spl.unwrap_or("").to_string())
}

/// Trim the given string with given patterns one after another
///
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(trim("nata", vec!["a"])?, "nat");
///     assert_eq!(trim("  \tnata\t  ", vec![])?, "nata");
///     assert_eq!(trim("hi there! ", vec![" ", "!"])?, "hi there");
///     assert_eq!(trim("hi there! ", vec![" !", "ih"])?, " there");
/// # Ok(())
/// # }
pub fn trim(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "trim";
    check_arguments_len(func_name, .., args.len())?;
    if args.is_empty() {
        return Ok(val.trim().to_string());
    }
    let mut val = val;
    for arg in args {
        val = val.trim_matches(|c| arg.contains(c))
    }

    Ok(val.to_string())
}

/// Insert commas to the given string in provided positions
///
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(comma("1234", vec!["3"])?, "1,234");
///     assert_eq!(comma("1234567", vec!["3"])?, "1,234,567");
///     assert_eq!(comma("1234567", vec!["3", "2"])?, "12,34,567");
///     assert_eq!(comma("91234567", vec!["3", "2"])?, "9,12,34,567");
/// # Ok(())
/// # }
pub fn comma(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "comma";
    check_arguments_len(func_name, 1.., args.len())?;
    let mut args: Vec<usize> = args
        .iter()
        .map(|s| {
            s.parse().map_err(|_| {
                TransformerError::InvalidArgumentType(func_name, s.to_string(), "uint")
            })
        })
        .rev()
        .collect::<Result<Vec<usize>, TransformerError>>()?;
    let last = args[0];
    let mut i = args.pop().unwrap();

    let mut result = vec![];
    let val: Vec<char> = val.replace(',', "").chars().rev().collect();
    for c in val {
        if i == 0 {
            i = args.pop().unwrap_or(last);
            result.push(',');
        }
        result.push(c);
        i -= 1;
    }
    result.reverse();
    let result: String = result.into_iter().collect();
    Ok(result)
}

/// Insert characters to the given string in provided positions
///
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(group("1234", vec![",", "3"])?, "1,234");
///     assert_eq!(group("1234567", vec!["_", "3"])?, "1_234_567");
///     assert_eq!(group("1234567", vec![", ", "3", "2"])?, "12, 34, 567");
///     assert_eq!(group("91234567", vec!["_", "3", "2"])?, "9_12_34_567");
/// # Ok(())
/// # }
pub fn group(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "group";
    check_arguments_len(func_name, 2.., args.len())?;
    let sep = args[0];
    let mut args: Vec<usize> = args[1..]
        .iter()
        .map(|s| {
            s.parse().map_err(|_| {
                TransformerError::InvalidArgumentType(func_name, s.to_string(), "uint")
            })
        })
        .rev()
        .collect::<Result<Vec<usize>, TransformerError>>()?;
    let last = args[0];
    let mut i = args.pop().unwrap();

    let mut result = vec![];
    let val: Vec<char> = val.replace(sep, "").chars().rev().collect();
    for c in val {
        if i == 0 {
            i = args.pop().unwrap_or(last);
            for c in sep.chars().rev() {
                result.push(c);
            }
        }
        result.push(c);
        i -= 1;
    }
    result.reverse();
    let result: String = result.into_iter().collect();
    Ok(result)
}

/// Quote the text with given strings or `""`
///
/// ```rust
/// # use std::error::Error;
/// # use string_template_plus::transformers::*;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
///     assert_eq!(quote("nata", vec![])?, "\"nata\"");
///     assert_eq!(quote("nata", vec!["'"])?, "'nata'");
///     assert_eq!(quote("na\"ta", vec![])?, "\"na\\\"ta\"");
///     assert_eq!(quote("na'ta", vec!["'"])?, "'na\\'ta'");
///     assert_eq!(quote("nata", vec!["`", "'"])?, "`nata'");
/// # Ok(())
/// # }
pub fn quote(val: &str, args: Vec<&str>) -> Result<String, TransformerError> {
    let func_name = "quote";
    check_arguments_len(func_name, ..=2, args.len())?;
    Ok(if args.is_empty() {
        format!("{:?}", val)
    } else if args.len() == 1 {
        if args[0].is_empty() {
            format!("{:?}", val)
        } else {
            format!(
                "{0}{1}{0}",
                args[0],
                val.replace(args[0], &format!("\\{}", args[0]))
            )
        }
    } else {
        format!(
            "{}{}{}",
            args[0],
            val.replace(args[0], &format!("\\{}", args[0]))
                .replace(args[1], &format!("\\{}", args[1])),
            args[1]
        )
    })
}