major-pickems-sim 0.3.0

Tool for analysing pick'ems for Counter-Strike major tournaments.
Documentation
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
475
476
477
use anyhow::anyhow;
use ratatui::{
    Frame,
    crossterm::event,
    layout::{Constraint, Layout, Rect},
    style::{Color, Modifier, Style, Stylize},
    text::Text,
    widgets::{
        Block, BorderType, Borders, Cell, HighlightSpacing, Paragraph, Row, Table, TableState,
    },
};
use ratatui_textarea::{Input, Key, TextArea};

use pickems::datatypes::{Map, Name, Rating, Seed, Team};

/// Footer content to render when in browse mode.
const BROWSE_FOOTER: [&str; 2] = [
    "(Esc) quit | (Ctrl + S) save | (Ctrl + N) add team | (Del) remove team",
    "(↑) up | (↓) down | (←) left | (→) right | (Enter) edit field",
];

/// Footer content to render when in edit mode.
const EDITOR_FOOTER: &str = "(Esc) cancel edit | (Enter) commit edit";

/// Interactive data-entry wizard backed by `ratatui`.
pub struct Wizard<'a> {
    save: bool,
    cancel: bool,
    teams: Vec<(Name, Team)>,
    problems: Vec<String>,
    state: TableState,
    editor: Option<TextArea<'a>>,
}

impl Wizard<'_> {
    /// Run an instance of the wizard to completion, handling ratatui and returning a vector of teams.
    pub fn run() -> anyhow::Result<Option<Map>> {
        let mut wizard = Self {
            save: false,
            cancel: false,
            teams: Vec::with_capacity(16),
            problems: Vec::with_capacity(4),
            state: TableState::default().with_selected(0),
            editor: None,
        };

        for _ in 0..16 {
            wizard.add_new_team();
        }

        let mut terminal = ratatui::init();

        while !(wizard.cancel || wizard.save) {
            if let Err(e) = {
                terminal.draw(|frame| wizard.render(frame))?;
                wizard.handle_crossterm_events()?;
                Ok(())
            } {
                ratatui::restore();
                return Err(e);
            }
        }

        ratatui::restore();

        if wizard.save {
            Ok(Some(Map::from(wizard.teams)))
        } else {
            Ok(None)
        }
    }

    /// Handle crossterm events and dispatch key inputs.
    fn handle_crossterm_events(&mut self) -> anyhow::Result<()> {
        if let Some(editor) = self.editor.as_mut() {
            match event::read()?.into() {
                Input {
                    key: Key::Char('c' | 'C'),
                    ctrl: true,
                    ..
                } => self.cancel = true,
                Input { key: Key::Esc, .. } => self.editor = None,
                Input {
                    key: Key::Enter, ..
                } => self.commit_edit(),
                input => {
                    if editor.input(input) {
                        self.validate_editor();
                    }
                }
            }
        } else {
            match event::read()?.into() {
                Input { key: Key::Esc, .. }
                | Input {
                    key: Key::Char('c' | 'C'),
                    ctrl: true,
                    ..
                } => self.cancel = true,
                Input {
                    key: Key::Char('s' | 'S'),
                    ctrl: true,
                    ..
                } if self.problems.is_empty() => {
                    self.save = true;
                }
                Input {
                    key: Key::Char('n' | 'N'),
                    ctrl: true,
                    ..
                } => self.add_new_team(),
                Input {
                    key: Key::Delete, ..
                } => self.remove_selected_team(),
                Input {
                    key: Key::Enter, ..
                } => self.start_edit(),
                Input {
                    key: Key::Down | Key::Char('j'),
                    ..
                } => self.next_row(),
                Input {
                    key: Key::Up | Key::Char('k'),
                    ..
                } => self.previous_row(),
                Input {
                    key: Key::Right | Key::Char('l'),
                    ..
                } => self.next_column(),
                Input {
                    key: Key::Left | Key::Char('h'),
                    ..
                } => self.previous_column(),
                _ => {}
            }
        }

        Ok(())
    }

    /// Attempt to parse current editor contents into a valid team.
    fn parse_edit(&self) -> anyhow::Result<(Name, Team)> {
        if let Some((row, col)) = self.state.selected_cell() {
            let (mut name, mut data) = self.teams[row].clone();

            if let Some(editor) = &self.editor {
                match col {
                    0 => {
                        let seed = Seed::try_new(editor.lines()[0].parse::<u16>()?)?;
                        data.seed = seed;
                        Ok((name, data))
                    }
                    1 => {
                        let new_name = Name::try_new(&editor.lines()[0])?;

                        if self.teams.iter().any(|(name, _)| name == &new_name) {
                            Err(anyhow!("name already exists, must be unique"))
                        } else {
                            name.clone_from(&new_name);
                            Ok((name, data))
                        }
                    }
                    2 => {
                        data.rating = Rating::try_new(editor.lines()[0].parse::<u16>()?)?;
                        Ok((name, data))
                    }
                    _ => unreachable!(),
                }
            } else {
                Err(anyhow!("failed to access editor (cancel edit and retry)"))
            }
        } else {
            Err(anyhow!("failed to select team (cancel edit and retry)"))
        }
    }

    /// Validate that current editor contents will produce a team.
    fn validate_editor(&mut self) -> bool {
        let parse = self.parse_edit();

        self.editor.as_mut().is_some_and(|editor| {
            if let Err(err) = parse {
                editor.set_block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_type(BorderType::Rounded)
                        .border_style(Color::LightRed)
                        .title(format!("ERROR: {err}")),
                );
                false
            } else {
                editor.set_block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_type(BorderType::Rounded)
                        .border_style(Color::LightGreen)
                        .title("OK"),
                );
                true
            }
        })
    }

    /// Start edit mode on the currently selected cell.
    fn start_edit(&mut self) {
        if let Some((_, col)) = self.state.selected_cell() {
            let mut textarea = TextArea::default();

            let placeholder = match col {
                0 => "Enter a valid seed (1-16)",
                1 => "Enter the team name",
                2 => "Enter the global ranking points for the team",
                _ => unreachable!(),
            };

            textarea.set_placeholder_text(placeholder);
            self.editor = Some(textarea);

            // Validate immediately so an empty editor shows the correct state.
            self.validate_editor();
        }
    }

    /// Commit current editor contents and exit editor if it is valid.
    fn commit_edit(&mut self) {
        if let Ok(team) = self.parse_edit() {
            if let Some(index) = self.state.selected() {
                self.teams[index] = team;
            } else {
                self.teams.push(team);
            }

            self.on_teams_change();
            self.editor = None;
        }
    }

    /// Add a new team to the table.
    fn add_new_team(&mut self) {
        let seeds = self
            .teams
            .iter()
            .map(|(_, data)| data.seed)
            .collect::<Vec<_>>();

        let Some(seed) = Seed::iter_all().find(|n| !seeds.contains(n)) else {
            return;
        };

        let name = Name::try_new(format!("Team {seed}")).unwrap();
        let rating = Rating::try_new(1000).unwrap();
        self.teams.push((name, Team { seed, rating }));

        self.on_teams_change();

        self.state.select(
            self.teams
                .iter()
                .enumerate()
                .find_map(|(i, (_, data))| if data.seed == seed { Some(i) } else { None }),
        );
    }

    /// Remove the team at the currently selected row.
    fn remove_selected_team(&mut self) {
        if let Some(i) = self.state.selected() {
            self.teams.remove(i);

            if i >= self.teams.len() {
                self.state.select(self.teams.len().checked_sub(1));
            }
        }

        self.on_teams_change();
    }

    /// Resort teams and check for problems. Call when the teams vec is changed.
    fn on_teams_change(&mut self) {
        self.teams.sort_by_key(|(_, a)| a.seed);
        self.problems.clear();

        if self.teams.len() < 16 {
            self.problems
                .push(format!("Not enough teams ({}/16)", self.teams.len()));
        }

        let seeds = self
            .teams
            .iter()
            .map(|(_, data)| data.seed)
            .collect::<Vec<_>>();

        for seed in &seeds {
            if !Seed::iter_all().any(|valid_seed| valid_seed == *seed) {
                self.problems.push(format!("Invalid seed ({seed})"));
            }
        }

        for i in Seed::iter_all() {
            if seeds.iter().filter(|&&seed| seed == i).count() > 1 {
                self.problems.push(format!("Duplicate seed ({i})"));
            }
        }

        // `Name` equality is case-insensitive, so this catches names that only
        // differ by case as duplicates too.
        for (i, (name, _)) in self.teams.iter().enumerate() {
            if self
                .teams
                .iter()
                .skip(i + 1)
                .any(|(other_name, _)| name == other_name)
            {
                self.problems.push(format!("Duplicate name ({name})"));
            }
        }
    }

    /// Move the cursor to the next row.
    const fn next_row(&mut self) {
        let i = match self.state.selected() {
            Some(i) => {
                if i >= self.teams.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };

        self.state.select(Some(i));
    }

    /// Move the cursor to the previous row.
    const fn previous_row(&mut self) {
        let i = match self.state.selected() {
            Some(i) => {
                if i == 0 {
                    self.teams.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };

        self.state.select(Some(i));
    }

    /// Move the cursor to the next column.
    fn next_column(&mut self) {
        self.state.select_next_column();
    }

    /// Move the cursor to the previous column.
    fn previous_column(&mut self) {
        self.state.select_previous_column();
    }

    /// Render the user interface.
    #[allow(clippy::cast_possible_truncation)]
    fn render(&mut self, frame: &mut Frame) {
        let rects = Layout::vertical([
            Constraint::Min(17),
            Constraint::Length(if self.problems.is_empty() {
                1
            } else {
                self.problems.len() as u16 + 2
            }),
            Constraint::Length(if self.editor.is_some() { 3 } else { 0 }),
            Constraint::Length(if self.editor.is_some() { 3 } else { 4 }),
        ])
        .split(frame.area());

        self.render_table(frame, rects[0]);
        self.render_problems(frame, rects[1]);
        self.render_editor(frame, rects[2]);
        self.render_footer(frame, rects[3]);
    }

    /// Render the table displaying the teams.
    fn render_table(&mut self, frame: &mut Frame, area: Rect) {
        let header_style = Style::default();

        let selected_row_style = if self.editor.is_some() {
            Style::default()
        } else {
            Style::default().add_modifier(Modifier::REVERSED)
        };

        let selected_cell_style = if self.editor.is_some() {
            Style::default()
                .add_modifier(Modifier::BOLD)
                .add_modifier(Modifier::UNDERLINED)
                .add_modifier(Modifier::REVERSED)
        } else {
            Style::default()
                .add_modifier(Modifier::BOLD)
                .add_modifier(Modifier::UNDERLINED)
        };

        let header = ["Seed", "Team", "Rating"]
            .into_iter()
            .map(Cell::from)
            .collect::<Row>()
            .style(header_style)
            .height(1);

        let rows = self.teams.iter().map(|(name, data)| {
            let item = [
                format!(" {}.", data.seed),
                name.to_string(),
                format!("{}", data.rating),
            ];

            item.into_iter()
                .map(|content| Cell::from(Text::from(content)))
                .collect::<Row>()
                .height(1)
        });

        let t = Table::new(
            rows,
            [
                Constraint::Length(7),
                Constraint::Min(20),
                Constraint::Min(8),
            ],
        )
        .header(header)
        .row_highlight_style(selected_row_style)
        .cell_highlight_style(selected_cell_style)
        .highlight_spacing(HighlightSpacing::Always);

        frame.render_stateful_widget(t, area, &mut self.state);
    }

    /// Render any detected problems.
    fn render_problems(&self, frame: &mut Frame, area: Rect) {
        let problems = if self.problems.is_empty() {
            Paragraph::new(Text::from("No problems")).light_green()
        } else {
            Paragraph::new(self.problems.iter().map(String::as_str).collect::<Text>()).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(Color::LightRed)
                    .title("Problems"),
            )
        };

        frame.render_widget(problems, area);
    }

    /// Render the editor when in edit mode.
    fn render_editor(&self, frame: &mut Frame, area: Rect) {
        if let Some(editor) = &self.editor {
            frame.render_widget(editor, area);
        }
    }

    /// Render the footer showing common keybinds.
    fn render_footer(&self, frame: &mut Frame, area: Rect) {
        let footer = if self.editor.is_some() {
            Paragraph::new(Text::from(EDITOR_FOOTER))
                .centered()
                .block(Block::bordered().border_type(BorderType::Rounded))
        } else {
            Paragraph::new(Text::from_iter(BROWSE_FOOTER))
                .centered()
                .block(Block::bordered().border_type(BorderType::Rounded))
        };

        frame.render_widget(footer, area);
    }
}