aboutsummaryrefslogtreecommitdiff
path: root/crates/cli/src/run.rs
blob: 0cce6d6a7e74c09e3cb62e87bbae29bf50124fe5 (plain)
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
use inquire::Text;
use mihi::{select_random_words, update_success, Category, Word};

// Maximum number of times a word has to be run in order to increase the number
// of successful runs.
const MAX_STEPS: usize = 5;

fn help(msg: Option<&str>) {
    if msg.is_some() {
        println!("{}.\n", msg.unwrap());
    }

    println!("mihi run: Run exercises. Default command if none was given.\n");
    println!("usage: mihi run [OPTIONS]\n");

    println!("Options:");
    println!("   -h, --help\t\tPrint this message.");
}

enum Locale {
    English,
    Catalan,
}

impl Locale {
    fn to_code(&self) -> &str {
        match self {
            Self::English => "en",
            Self::Catalan => "ca",
        }
    }
}

impl std::fmt::Display for Locale {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::English => write!(f, "english"),
            Self::Catalan => write!(f, "català"),
        }
    }
}

fn run_words(words: Vec<Word>, locale: Locale) -> i32 {
    let mut errors = 0;

    for word in words {
        // If the translation cannot be found, skip this word.
        let Some(translation) = word.translation.get(locale.to_code()) else {
            continue;
        };

        println!("Word: {}", word.enunciated);

        let Ok(raw) = Text::new(format!("Translation ({}):", locale).as_str()).prompt() else {
            return 1;
        };
        let answer = raw.trim();

        let tr = translation.as_str().unwrap_or("");
        let found = !answer.is_empty() && tr.split(',').any(|tr| tr.trim().contains(&answer));

        if found {
            if word.steps == MAX_STEPS - 1 {
                let _ = update_success(&word, word.succeeded + 1, 0);
            } else {
                let _ = update_success(&word, word.succeeded, word.steps + 1);
            }
            println!("\x1b[92m✓ {}\x1b[0m", tr);
        } else {
            if word.succeeded > 0 {
                let _ = update_success(&word, word.succeeded - 1, 0);
            }
            println!("\x1b[91m❌{}\x1b[0m", tr);
            errors += 1;
        }
    }

    errors
}

fn select_general_words() -> Result<Vec<Word>, String> {
    let mut res = select_random_words(Category::Noun, 4)?;
    res.append(&mut select_random_words(Category::Adjective, 2)?);
    res.append(&mut select_random_words(Category::Verb, 4)?);
    res.append(&mut select_random_words(Category::Pronoun, 1)?);
    res.append(&mut select_random_words(Category::Adverb, 2)?);
    res.append(&mut select_random_words(Category::Preposition, 1)?);
    res.append(&mut select_random_words(Category::Conjunction, 1)?);
    Ok(res)
}

pub fn run(args: Vec<String>) {
    let mut it = args.into_iter();
    let mut category = None;

    while let Some(first) = it.next() {
        match first.as_str() {
            "-h" | "--help" => {
                help(None);
                std::process::exit(0);
            }
            "-c" | "--category" => {
                if category.is_some() {
                    help(Some("error: run: you cannot provide multiple categories"));
                }
                match it.next() {
                    Some(cat) => {
                        category = match cat.trim().to_lowercase().as_str() {
                            "noun" => Some(Category::Noun),
                            "adjective" => Some(Category::Adjective),
                            "verb" => Some(Category::Verb),
                            "pronoun" => Some(Category::Pronoun),
                            "adverb" => Some(Category::Adverb),
                            "preposition" => Some(Category::Preposition),
                            "conjunction" => Some(Category::Conjunction),
                            "determiner" => Some(Category::Determiner),
                            _ => return help(Some("error: run: category not allowed")),
                        };
                    }
                    None => help(Some("error: run: you have to provide a category")),
                }
            }
            _ => {
                help(Some(
                    format!("error: run: unknown flag or command '{}'", first).as_str(),
                ));
                std::process::exit(1);
            }
        }
    }

    let raw_locale = std::env::var("LC_ALL").unwrap_or("en".to_string());
    let locale = if raw_locale.starts_with("ca") {
        Locale::Catalan
    } else {
        Locale::English
    };

    let words = match category {
        Some(cat) => select_random_words(cat, 15),
        None => select_general_words(),
    };

    match words {
        Ok(list) => std::process::exit(run_words(list, locale)),
        Err(e) => {
            println!("error: run: {}", e);
            std::process::exit(1);
        }
    };
}