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
pub use alias::CommandAlias;
pub use app::AppCommand;
pub use runnable::{
    Autocomplete, AutocompleteSuggestion, CommandMatches, ContextAwareParse, Runnable,
};
pub use tutorial::TutorialCommand;

#[cfg(test)]
pub use runnable::assert_autocomplete;

mod alias;
mod app;
mod runnable;
mod tutorial;

use super::AppMeta;
use crate::reference::ReferenceCommand;
use crate::storage::StorageCommand;
use crate::time::TimeCommand;
use crate::world::WorldCommand;
use async_trait::async_trait;
use futures::join;
use std::fmt;

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Command {
    matches: CommandMatches<CommandType>,
}

impl Command {
    pub fn get_type(&self) -> Option<&CommandType> {
        let command_type = if let Some(command) = &self.matches.canonical_match {
            Some(command)
        } else if self.matches.fuzzy_matches.len() == 1 {
            self.matches.fuzzy_matches.first()
        } else {
            None
        };

        if let Some(CommandType::Alias(alias)) = command_type {
            alias.get_command().get_type()
        } else {
            command_type
        }
    }

    pub async fn parse_input_irrefutable(input: &str, app_meta: &AppMeta) -> Self {
        let parse_results = join!(
            CommandAlias::parse_input(input, app_meta),
            AppCommand::parse_input(input, app_meta),
            ReferenceCommand::parse_input(input, app_meta),
            StorageCommand::parse_input(input, app_meta),
            TimeCommand::parse_input(input, app_meta),
            TutorialCommand::parse_input(input, app_meta),
            WorldCommand::parse_input(input, app_meta),
        );

        // We deliberately skip parse_results.0 and handle it afterwards.
        let mut result = CommandMatches::default()
            .union(parse_results.1)
            .union(parse_results.2)
            .union(parse_results.3)
            .union(parse_results.4)
            .union(parse_results.5)
            .union(parse_results.6);

        // While it is normally a fatal error to encounter two command subtypes claiming canonical
        // matches on a given input, the exception is where aliases are present. In this case, we
        // want the alias to overwrite the canonical match that would otherwise be returned.
        result = result.union_with_overwrite(parse_results.0);

        result.into()
    }
}

impl From<CommandMatches<CommandType>> for Command {
    fn from(input: CommandMatches<CommandType>) -> Self {
        Self { matches: input }
    }
}

#[async_trait(?Send)]
impl Runnable for Command {
    async fn run(self, input: &str, app_meta: &mut AppMeta) -> Result<String, String> {
        if let Some(command) = &self.matches.canonical_match {
            let other_interpretations_message = if !self.matches.fuzzy_matches.is_empty()
                && !matches!(
                    command,
                    CommandType::Alias(CommandAlias::StrictWildcard { .. })
                ) {
                let mut message = "\n\n! There are other possible interpretations of this command. Did you mean:\n".to_string();
                let mut lines: Vec<_> = self
                    .matches
                    .fuzzy_matches
                    .iter()
                    .map(|command| format!("\n* `{}`", command))
                    .collect();
                lines.sort();
                lines.into_iter().for_each(|line| message.push_str(&line));
                Some(message)
            } else {
                None
            };

            let result = self
                .matches
                .canonical_match
                .unwrap()
                .run(input, app_meta)
                .await;
            if let Some(message) = other_interpretations_message {
                result
                    .map(|mut s| {
                        s.push_str(&message);
                        s
                    })
                    .map_err(|mut s| {
                        s.push_str(&message);
                        s
                    })
            } else {
                result
            }
        } else {
            match &self.matches.fuzzy_matches.len() {
                0 => Err(format!("Unknown command: \"{}\"", input)),
                1 => {
                    let mut fuzzy_matches = self.matches.fuzzy_matches;
                    fuzzy_matches.pop().unwrap().run(input, app_meta).await
                }
                _ => {
                    let mut message =
                        "There are several possible interpretations of this command. Did you mean:\n"
                            .to_string();
                    let mut lines: Vec<_> = self
                        .matches
                        .fuzzy_matches
                        .iter()
                        .map(|command| format!("\n* `{}`", command))
                        .collect();
                    lines.sort();
                    lines.into_iter().for_each(|line| message.push_str(&line));
                    Err(message)
                }
            }
        }
    }
}

#[async_trait(?Send)]
impl ContextAwareParse for Command {
    async fn parse_input(input: &str, app_meta: &AppMeta) -> CommandMatches<Self> {
        CommandMatches::new_canonical(Self::parse_input_irrefutable(input, app_meta).await)
    }
}

#[async_trait(?Send)]
impl Autocomplete for Command {
    async fn autocomplete(input: &str, app_meta: &AppMeta) -> Vec<AutocompleteSuggestion> {
        let results = join!(
            CommandAlias::autocomplete(input, app_meta),
            AppCommand::autocomplete(input, app_meta),
            ReferenceCommand::autocomplete(input, app_meta),
            StorageCommand::autocomplete(input, app_meta),
            TimeCommand::autocomplete(input, app_meta),
            TutorialCommand::autocomplete(input, app_meta),
            WorldCommand::autocomplete(input, app_meta),
        );

        std::iter::empty()
            .chain(results.0)
            .chain(results.1)
            .chain(results.2)
            .chain(results.3)
            .chain(results.4)
            .chain(results.5)
            .chain(results.6)
            .collect()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CommandType {
    Alias(CommandAlias),
    App(AppCommand),
    Reference(ReferenceCommand),
    Storage(StorageCommand),
    Time(TimeCommand),
    Tutorial(TutorialCommand),
    World(WorldCommand),
}

impl CommandType {
    async fn run(self, input: &str, app_meta: &mut AppMeta) -> Result<String, String> {
        if !matches!(self, Self::Alias(_) | Self::Tutorial(_)) {
            app_meta.command_aliases.clear();
        }

        match self {
            Self::Alias(c) => c.run(input, app_meta).await,
            Self::App(c) => c.run(input, app_meta).await,
            Self::Reference(c) => c.run(input, app_meta).await,
            Self::Storage(c) => c.run(input, app_meta).await,
            Self::Time(c) => c.run(input, app_meta).await,
            Self::Tutorial(c) => c.run(input, app_meta).await,
            Self::World(c) => c.run(input, app_meta).await,
        }
    }
}

impl fmt::Display for CommandType {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match self {
            Self::Alias(c) => write!(f, "{}", c),
            Self::App(c) => write!(f, "{}", c),
            Self::Reference(c) => write!(f, "{}", c),
            Self::Storage(c) => write!(f, "{}", c),
            Self::Time(c) => write!(f, "{}", c),
            Self::Tutorial(c) => write!(f, "{}", c),
            Self::World(c) => write!(f, "{}", c),
        }
    }
}

impl<T: Into<CommandType>> From<T> for Command {
    fn from(c: T) -> Command {
        Command {
            matches: CommandMatches::new_canonical(c.into()),
        }
    }
}

impl From<AppCommand> for CommandType {
    fn from(c: AppCommand) -> CommandType {
        CommandType::App(c)
    }
}

impl From<CommandAlias> for CommandType {
    fn from(c: CommandAlias) -> CommandType {
        CommandType::Alias(c)
    }
}

impl From<ReferenceCommand> for CommandType {
    fn from(c: ReferenceCommand) -> CommandType {
        CommandType::Reference(c)
    }
}

impl From<StorageCommand> for CommandType {
    fn from(c: StorageCommand) -> CommandType {
        CommandType::Storage(c)
    }
}

impl From<TimeCommand> for CommandType {
    fn from(c: TimeCommand) -> CommandType {
        CommandType::Time(c)
    }
}

impl From<TutorialCommand> for CommandType {
    fn from(c: TutorialCommand) -> CommandType {
        CommandType::Tutorial(c)
    }
}

impl From<WorldCommand> for CommandType {
    fn from(c: WorldCommand) -> CommandType {
        CommandType::World(c)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::app::assert_autocomplete;
    use crate::storage::NullDataStore;
    use crate::world::npc::NpcData;
    use crate::world::ParsedThing;
    use crate::Event;
    use tokio_test::block_on;

    #[test]
    fn parse_input_test() {
        let app_meta = app_meta();

        assert_eq!(
            Command::from(CommandMatches::new_canonical(CommandType::App(
                AppCommand::About
            ))),
            block_on(Command::parse_input("about", &app_meta))
                .take_best_match()
                .unwrap(),
        );

        assert_eq!(
            Command::from(CommandMatches::new_canonical(CommandType::Reference(
                ReferenceCommand::OpenGameLicense
            ))),
            block_on(Command::parse_input("Open Game License", &app_meta))
                .take_best_match()
                .unwrap(),
        );

        assert_eq!(
            Command::from(CommandMatches::default()),
            block_on(Command::parse_input("Gandalf the Grey", &app_meta))
                .take_best_match()
                .unwrap(),
        );

        assert_eq!(
            Command::from(CommandMatches::new_canonical(CommandType::World(
                WorldCommand::Create {
                    parsed_thing_data: ParsedThing {
                        thing_data: NpcData::default().into(),
                        unknown_words: Vec::new(),
                        word_count: 1,
                    },
                }
            ))),
            block_on(Command::parse_input("create npc", &app_meta))
                .take_best_match()
                .unwrap(),
        );
    }

    #[test]
    fn autocomplete_test() {
        assert_autocomplete(
            &[
                ("Dancing Lights", "SRD spell"),
                ("Darkness", "SRD spell"),
                ("Darkvision", "SRD spell"),
                ("date", "get the current time"),
                ("Daylight", "SRD spell"),
                ("Death Ward", "SRD spell"),
                ("Delayed Blast Fireball", "SRD spell"),
                ("delete [name]", "remove an entry from journal"),
                ("Demiplane", "SRD spell"),
                ("desert", "create desert"),
                ("Detect Evil and Good", "SRD spell"),
                ("Detect Magic", "SRD spell"),
                ("Detect Poison and Disease", "SRD spell"),
                ("distillery", "create distillery"),
                ("district", "create district"),
                ("domain", "create domain"),
                ("dragonborn", "create dragonborn"),
                ("duchy", "create duchy"),
                ("duty-house", "create duty-house"),
                ("dwarf", "create dwarf"),
                ("dwarvish", "create dwarvish person"),
            ][..],
            block_on(Command::autocomplete("d", &app_meta())),
        );
    }

    #[test]
    fn into_command_test() {
        assert_eq!(
            CommandType::App(AppCommand::Debug),
            AppCommand::Debug.into(),
        );

        assert_eq!(
            CommandType::Storage(StorageCommand::Load {
                name: "Gandalf the Grey".to_string(),
            }),
            StorageCommand::Load {
                name: "Gandalf the Grey".to_string(),
            }
            .into(),
        );

        assert_eq!(
            CommandType::World(WorldCommand::Create {
                parsed_thing_data: ParsedThing {
                    thing_data: NpcData::default().into(),
                    unknown_words: Vec::new(),
                    word_count: 1,
                },
            }),
            WorldCommand::Create {
                parsed_thing_data: ParsedThing {
                    thing_data: NpcData::default().into(),
                    unknown_words: Vec::new(),
                    word_count: 1,
                },
            }
            .into(),
        );
    }

    fn event_dispatcher(_event: Event) {}

    fn app_meta() -> AppMeta {
        AppMeta::new(NullDataStore, &event_dispatcher)
    }
}