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
use std::{collections::HashMap, error::Error, fs::File, io::Read, path::PathBuf, str::from_utf8};

use rand::seq::SliceRandom;
use regex::Regex;
use rust_embed::RustEmbed;

use crate::bubbles::{BubbleType, SpeechBubble};

pub mod bubbles;
pub mod errors;

#[derive(RustEmbed, Debug)]
#[folder = "src/charas"]
struct Asset;

/// Source chara to load, either builtin or from external file.
#[derive(Debug)]
pub enum Chara {
    All,
    Builtin(String),
    File(PathBuf),
    Raw(String),
    Random,
}

/// All built-in characters name.
pub const BUILTIN_CHARA: [&str; 23] = [
    "aya",
    "cirno",
    "clefairy",
    "cow",
    "eevee",
    "ferris",
    "ferris1",
    "flareon",
    "goldeen",
    "growlithe",
    "kirby",
    "kitten",
    "mario",
    "mew",
    "nemo",
    "pikachu",
    "piplup",
    "psyduck",
    "remilia-scarlet",
    "seaking",
    "togepi",
    "tux",
    "wartortle",
];

fn load_raw_chara_string(chara: &Chara) -> String {
    let mut raw_chara = String::new();

    match chara {
        Chara::File(s) => {
            let mut file = File::open(s).unwrap_or_else(|err| todo!("Log ERROR: {:#?}", err));
            file.read_to_string(&mut raw_chara)
                .unwrap_or_else(|err| todo!("Log ERROR: {:#?}", err));
        }

        Chara::Builtin(s) => {
            let name = format!("{}.chara", s);
            let asset = Asset::get(&name).unwrap();
            raw_chara = from_utf8(&asset.data)
                .unwrap_or_else(|err| todo!("Log ERROR: {:#?}", err))
                .to_string();
        }

        Chara::Raw(s) => {
            raw_chara = s.to_string();
        }

        Chara::All => {
            let charas = Asset::iter()
                .map(|file| {
                    let name = file.trim_end_matches(".chara");
                    let asset = Asset::get(&file).unwrap();
                    format!("{} 👇\n{}", name, String::from_utf8_lossy(&asset.data))
                })
                .collect::<Vec<_>>();
            raw_chara = charas.join("\n+\n");
        }

        Chara::Random => {
            let charas = Asset::iter().collect::<Vec<_>>();
            let choosen_chara = charas.choose(&mut rand::thread_rng()).unwrap().clone();
            let asset = Asset::get(&choosen_chara).unwrap();
            raw_chara = from_utf8(&asset.data)
                .unwrap_or_else(|err| todo!("Log ERROR: {:#?}", err))
                .to_string();
        }
    }

    raw_chara
}

fn strip_chara_string(raw_chara: &str) -> String {
    raw_chara
        .split('\n')
        .filter(|line| {
            !line.starts_with('#')
                && !line.starts_with("$x")
                && !line.contains("$thoughts")
                && !line.is_empty()
        })
        .collect::<Vec<_>>()
        .join("\n")
        .replace("\\e", "\x1B")
}

fn parse_character(chara: &Chara, voice_line: &str) -> String {
    let raw_chara = load_raw_chara_string(chara);
    let stripped_chara = strip_chara_string(&raw_chara);
    let charas = stripped_chara.split('+').collect::<Vec<_>>();
    let mut parsed = String::new();

    for chara in charas {
        // extract variable definition to HashMap
        let re = Regex::new(r"(?<var>\$\w).*=.*(?<val>\x1B\[.*m\s*).;").unwrap();
        let replacers: Vec<HashMap<&str, &str>> = re
            .captures_iter(chara)
            .map(|cap| {
                re.capture_names()
                    .flatten()
                    .filter_map(|n| Some((n, cap.name(n)?.as_str())))
                    .collect()
            })
            .collect();

        let mut chara_body = chara
            .split('\n')
            .filter(|line| !line.contains('=') && !line.contains("EOC"))
            .collect::<Vec<_>>()
            .join("\n")
            .trim_end()
            .replace("$x", "\x1B[49m  ")
            .replace("$t", voice_line);

        // replace variable from character's body with actual value
        for replacer in replacers {
            chara_body = chara_body.replace(
                replacer.get("var").copied().unwrap(),
                replacer.get("val").copied().unwrap(),
            );
        }

        parsed.push_str(&format!("{}\n\n\n", &chara_body))
    }

    parsed.trim_end().to_string()
}

/// Format arguments to form complete charasay
pub fn format_character(
    messages: &str,
    chara: &Chara,
    max_width: usize,
    bubble_type: BubbleType,
) -> Result<String, Box<dyn Error>> {
    let voice_line: &str;
    let bubble_type = match bubble_type {
        BubbleType::Think => {
            voice_line = "o ";
            BubbleType::Think
        }
        BubbleType::Round => {
            voice_line = "╲ ";
            BubbleType::Round
        }
        BubbleType::Cowsay => {
            voice_line = "\\ ";
            BubbleType::Cowsay
        }
        BubbleType::Ascii => {
            voice_line = "\\ ";
            BubbleType::Ascii
        }
        BubbleType::Unicode => {
            voice_line = "╲ ";
            BubbleType::Unicode
        }
    };

    let speech_bubble = SpeechBubble::new(bubble_type);
    let speech = speech_bubble.create(messages, &max_width)?;
    let character = parse_character(chara, voice_line);

    Ok(format!("{}{}", speech, character))
}

/// Print only the character
pub fn print_character(chara: &Chara) -> String {
    parse_character(chara, "  ")
}