mlbt 0.3.0

A terminal user interface for the MLB stats API. Watch a baseball game in your terminal! ⚾
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use crate::components::constants::{DIVISION_ORDERS, DIVISIONS, lookup_team, lookup_team_by_id};
use crate::components::date_selector::DateSelector;
use crate::components::util::win_pct_color;
use crate::state::team_page::TeamPageState;
use chrono::NaiveDate;
use chrono_tz::Tz;
use mlbt_api::player::PeopleResponse;
use mlbt_api::schedule::ScheduleResponse;
use mlbt_api::season::GameType;
use mlbt_api::standings::{RecordElement, StandingsResponse, TeamRecord};
use mlbt_api::team::{RosterResponse, RosterType, TransactionsResponse};
use std::collections::HashSet;
use std::string::ToString;
use std::sync::Arc;
use tui::prelude::{Color, Stylize};
use tui::widgets::{Cell, TableState};

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ViewMode {
    ByDivision,
    Overall,
}

/// Stores the state for rendering the standings. The `standings` field is a nested Vec to make
/// displaying by division easier.
pub struct StandingsState {
    pub state: TableState,
    pub favorite_team: Option<Team>,
    pub standings: Vec<Division>,
    pub league_standings: Vec<Standing>,
    pub team_ids: Vec<u16>,
    pub date_selector: DateSelector,
    pub view_mode: ViewMode,
    /// Used to skip selecting division names in the table.
    division_row_indices: HashSet<usize>,
    pub team_page: Option<TeamPageState>,
}

/// Groups teams into their divisions.
pub struct Division {
    pub name: String,
    pub id: u16,
    pub standings: Vec<Standing>,
}

#[derive(Debug, Clone, Copy)]
pub struct Team {
    pub id: u16,
    pub division_id: u16,
    /// Full name, e.g. "Chicago Cubs"
    pub name: &'static str,
    /// Short name, e.g. "Cubs"
    pub team_name: &'static str,
    /// All caps abbreviation, e.g. "CHC"
    pub abbreviation: &'static str,
}

impl Default for Team {
    fn default() -> Self {
        Self {
            id: 0,
            division_id: 0,
            name: "unknown",
            team_name: "unknown",
            abbreviation: "UNK",
        }
    }
}

impl Team {
    /// Create a team from the schedule API response data.
    /// Uses `Box::leak` to promote strings to `&'static str`.
    pub fn from_schedule(team: &mlbt_api::schedule::IdNameLink) -> Self {
        let leaked: &'static str = Box::leak(team.name.clone().into_boxed_str());
        Self {
            id: team.id,
            name: leaked,
            team_name: leaked,
            abbreviation: leaked,
            ..Self::default()
        }
    }

    /// Create a team from the live game API response data.
    /// Uses `Box::leak` to promote strings to `&'static str`.
    pub fn from_live(team: &mlbt_api::live::Team) -> Self {
        Self {
            id: team.id,
            name: Box::leak(team.name.clone().into_boxed_str()),
            team_name: Box::leak(team.team_name.clone().into_boxed_str()),
            abbreviation: Box::leak(team.abbreviation.clone().into_boxed_str()),
            ..Self::default()
        }
    }
}

/// Standing information per team.
#[derive(Debug, Default, Clone)]
pub struct Standing {
    pub team: Team,
    pub wins: u8,
    pub losses: u8,
    pub winning_percentage: String,
    pub games_back: String,
    pub wild_card_games_back: String,
    pub last_10: String,
    pub streak: String,
    pub runs_scored: u16,
    pub runs_allowed: u16,
    pub run_differential: i16,
    pub xwl: String,
    pub home: String,
    pub away: String,
}

impl Default for StandingsState {
    fn default() -> Self {
        Self {
            state: TableState::default(),
            standings: Division::create_divisions(),
            league_standings: vec![],
            team_ids: vec![200, 201, 202, 203, 204, 205],
            date_selector: DateSelector::default(),
            view_mode: ViewMode::ByDivision,
            division_row_indices: HashSet::new(),
            favorite_team: None,
            team_page: None,
        }
    }
}

impl StandingsState {
    /// Update the data from the API.
    pub fn update(&mut self, standings: &StandingsResponse) {
        self.standings = Division::create_table(standings, self.favorite_team);
        self.league_standings = self.get_teams_by_record();
        self.team_ids = self.generate_ids();

        if self.standings.is_empty() {
            self.state.select(None);
        } else {
            self.reset_selection();
        }
    }

    pub fn reset_selection(&mut self) {
        if let Some(team) = self.favorite_team {
            self.select_favorite_team(team)
        } else if !self.team_ids.is_empty() {
            let offset = match self.view_mode {
                ViewMode::ByDivision => 1, // Skip first division header
                ViewMode::Overall => 0,    // No division headers to skip
            };
            self.state.select(Some(offset));
        }
    }

    /// Reapply the favorite team ordering/highlight to already loaded standings data.
    pub fn apply_favorite_team(&mut self, favorite_team: Option<Team>) {
        self.favorite_team = favorite_team;

        if !self
            .standings
            .iter()
            .any(|division| !division.standings.is_empty())
        {
            return;
        }

        Division::sort_by_favorite(&mut self.standings, favorite_team);
        self.league_standings = self.get_teams_by_record();
        self.team_ids = self.generate_ids();
        self.reset_selection();
    }

    /// Set the date from the validated input string from the date picker.
    pub fn set_date_from_valid_input(&mut self, date: NaiveDate) {
        self.date_selector.set_date_from_valid_input(date);
    }

    /// Set the date using Left/Right arrow keys to move a single day at a time.
    pub fn set_date_with_arrows(&mut self, forward: bool) -> NaiveDate {
        self.date_selector.set_date_with_arrows(forward)
    }

    /// Toggle between division view and overall view
    pub fn toggle_view_mode(&mut self) {
        self.view_mode = match self.view_mode {
            ViewMode::ByDivision => ViewMode::Overall,
            ViewMode::Overall => ViewMode::ByDivision,
        };
        self.team_ids = self.generate_ids();
        self.reset_selection();
    }

    /// Get all teams sorted by record (for overall view)
    fn get_teams_by_record(&self) -> Vec<Standing> {
        let mut teams: Vec<Standing> = self
            .standings
            .iter()
            .flat_map(|division| division.standings.iter())
            .cloned()
            .collect();

        teams.sort_by(|a, b| {
            // Sort by wins descending, then losses ascending
            b.wins.cmp(&a.wins).then(a.losses.cmp(&b.losses))
        });

        teams
    }

    fn generate_ids(&mut self) -> Vec<u16> {
        self.division_row_indices.clear(); // clear previous indices in case they change, e.g. historical standings

        match self.view_mode {
            ViewMode::ByDivision => {
                let mut ids = Vec::with_capacity(36); // 30 teams, 6 divisions
                let mut count = 0;
                for division in &self.standings {
                    ids.push(division.id);
                    self.division_row_indices.insert(count);
                    for team in &division.standings {
                        ids.push(team.team.id);
                    }
                    count += 1 + division.standings.len();
                }
                ids
            }
            ViewMode::Overall => {
                // For overall view, just collect team IDs without divisions
                self.league_standings
                    .iter()
                    .map(|standing| standing.team.id)
                    .collect()
            }
        }
    }

    fn select_favorite_team(&mut self, team: Team) {
        let idx = match self.view_mode {
            ViewMode::ByDivision => {
                // Find team position including division headers
                let mut current_idx = 0;
                for division in &self.standings {
                    current_idx += 1; // Skip division header
                    for standing in &division.standings {
                        if standing.team.id == team.id {
                            self.state.select(Some(current_idx));
                            return;
                        }
                        current_idx += 1;
                    }
                }
                None
            }
            ViewMode::Overall => {
                // Find team position in sorted list
                self.league_standings
                    .iter()
                    .position(|standing| standing.team.id == team.id)
            }
        };

        self.state.select(idx);
    }

    pub fn has_team_page(&self) -> bool {
        self.team_page.is_some()
    }

    /// Close the top layer overlay. If the overlay is a player profile, close it. Otherwise,
    /// close the team page.
    pub fn close_overlay(&mut self) {
        if let Some(tp) = &mut self.team_page {
            if tp.player_profile.is_some() {
                tp.player_profile = None;
            } else {
                self.team_page = None;
            }
        }
    }

    pub fn update_team_page(
        &mut self,
        team_id: u16,
        date: NaiveDate,
        schedule: &ScheduleResponse,
        roster: &RosterResponse,
        transactions: &TransactionsResponse,
        tz: Tz,
    ) {
        let team = lookup_team_by_id(team_id).unwrap_or_default();
        self.team_page = Some(TeamPageState::from_response(
            team,
            date,
            schedule,
            roster,
            transactions,
            tz,
        ));
    }

    pub fn update_team_roster(
        &mut self,
        team_id: u16,
        roster: &RosterResponse,
        roster_type: RosterType,
    ) {
        if let Some(tp) = &mut self.team_page
            && tp.team.id == team_id
        {
            tp.update_roster(roster, roster_type);
        }
    }

    pub fn update_team_player_profile(&mut self, data: Arc<PeopleResponse>, game_type: GameType) {
        if let Some(tp) = &mut self.team_page {
            tp.update_player_profile(data, game_type);
        }
    }

    pub fn get_selected(&self) -> u16 {
        let selected = self.state.selected().unwrap_or(0);
        if let Some(s) = self.team_ids.get(selected) {
            *s
        } else {
            0
        }
    }

    fn skip_division(&self, index: usize) -> bool {
        // Only skip division rows in division view mode
        self.view_mode == ViewMode::ByDivision && self.division_row_indices.contains(&index)
    }

    fn move_forward(&self, current: usize) -> usize {
        let len = self.team_ids.len();
        if current >= len - 1 { 0 } else { current + 1 }
    }

    fn move_backward(&self, current: usize) -> usize {
        let len = self.team_ids.len();
        if current == 0 { len - 1 } else { current - 1 }
    }

    pub fn next(&mut self) {
        let len = self.team_ids.len();
        if len == 0 {
            return;
        }

        let start = self.state.selected().unwrap_or(0);
        let mut i = self.move_forward(start);

        if self.skip_division(i) {
            i = self.move_forward(i);
        }

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

        // Reset offset when wrapping to beginning
        if i < start {
            self.state = TableState::default();
            self.state.select(Some(i));
        }
    }

    pub fn previous(&mut self) {
        let len = self.team_ids.len();
        if len == 0 {
            return;
        }

        let start = self.state.selected().unwrap_or(0);
        let mut i = self.move_backward(start);

        if self.skip_division(i) {
            i = self.move_backward(i);
        }

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

        // Reset offset when wrapping to end
        if i > start {
            self.state = TableState::default();
            self.state.select(Some(i));
        }
    }
}

impl Division {
    /// Generate only the division names.
    fn create_divisions() -> Vec<Division> {
        (200..206)
            .map(|id| Division {
                name: DIVISIONS[&id].to_string(),
                id,
                standings: vec![],
            })
            .collect()
    }

    /// Generate the standings data to be used to render a table widget.
    fn create_table(standings: &StandingsResponse, favorite_team: Option<Team>) -> Vec<Division> {
        let mut s: Vec<Division> = standings
            .records
            .iter()
            .map(|r| {
                // Pre-1969 seasons have no divisions, fall back to league.
                let group_id = r
                    .division
                    .as_ref()
                    .map(|d| d.id as u16)
                    .unwrap_or(r.league.id as u16);
                let group_name = DIVISIONS.get(&group_id).unwrap_or(&"Unknown").to_string();
                Division {
                    name: group_name,
                    id: group_id,
                    standings: r
                        .team_records
                        .iter()
                        .map(Standing::from_team_record)
                        .collect(),
                }
            })
            .collect();

        Self::sort_by_favorite(&mut s, favorite_team);
        s
    }

    fn sort_by_favorite(divisions: &mut [Division], favorite_team: Option<Team>) {
        if let Some(team) = favorite_team
            && let Some(order) = DIVISION_ORDERS.get(&team.division_id)
        {
            divisions.sort_by_key(|standing| {
                order
                    .iter()
                    .position(|&x| x == standing.id)
                    .unwrap_or(usize::MAX)
            });
            return;
        }

        // ensure display order is the same when there is no favorite team ordering
        divisions.sort_by(|a, b| a.id.cmp(&b.id));
    }
}

impl Standing {
    fn find_record(records: &[RecordElement], record_type: &str) -> String {
        records
            .iter()
            .find(|r| r.record_type.as_deref() == Some(record_type))
            .map(|r| format!("{}-{}", r.wins, r.losses))
            .unwrap_or_else(|| "-".to_string())
    }

    fn from_team_record(team: &TeamRecord) -> Self {
        let streak = team
            .streak
            .as_ref()
            .map(|s| s.streak_code.clone())
            .unwrap_or_else(|| "-".to_string());
        let last_10 = Self::find_record(&team.records.split_records, "lastTen");
        let home = Self::find_record(&team.records.overall_records, "home");
        let away = Self::find_record(&team.records.overall_records, "away");
        let xwl = team
            .records
            .expected_records
            .as_ref()
            .map(|records| Self::find_record(records, "xWinLoss"))
            .unwrap_or_else(|| "-".to_string());

        Standing {
            team: lookup_team(&team.team.name),
            wins: team.wins,
            losses: team.losses,
            winning_percentage: team.winning_percentage.clone(),
            games_back: team.games_back.clone(),
            wild_card_games_back: team.wild_card_games_back.clone(),
            last_10,
            streak,
            runs_scored: team.runs_scored,
            runs_allowed: team.runs_allowed,
            run_differential: team.run_differential,
            xwl,
            home,
            away,
        }
    }

    pub fn to_cells(&self) -> Vec<Cell<'_>> {
        let (prefix, rdiff_color) = match self.run_differential.signum() {
            1 => ("+", Color::Green),
            -1 => ("", Color::Red),
            _ => ("", Color::White),
        };
        let pct_color = win_pct_color(&self.winning_percentage).unwrap_or(Color::White);
        let streak_color = match self.streak.chars().next() {
            Some('W') => Color::Green,
            Some('L') => Color::Red,
            _ => Color::White,
        };
        vec![
            self.team.name.to_string().into(),
            self.wins.to_string().into(),
            self.losses.to_string().into(),
            Cell::from(self.winning_percentage.clone()).fg(pct_color),
            self.games_back.clone().into(),
            self.wild_card_games_back.clone().into(),
            self.last_10.clone().into(),
            Cell::from(self.streak.clone()).fg(streak_color),
            self.runs_scored.to_string().into(),
            self.runs_allowed.to_string().into(),
            Cell::from(format!("{}{}", prefix, self.run_differential)).fg(rdiff_color),
            self.xwl.clone().into(),
            self.home.clone().into(),
            self.away.clone().into(),
        ]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn standing(team_id: u16, wins: u8, losses: u8) -> Standing {
        Standing {
            team: lookup_team_by_id(team_id).unwrap(),
            wins,
            losses,
            ..Standing::default()
        }
    }

    #[test]
    fn apply_favorite_team_reorders_divisions_and_selects_team() {
        let mut state = StandingsState {
            state: TableState::default(),
            favorite_team: None,
            standings: vec![
                Division {
                    id: 200,
                    name: "AL West".to_string(),
                    standings: vec![standing(108, 10, 5)],
                },
                Division {
                    id: 201,
                    name: "AL East".to_string(),
                    standings: vec![standing(147, 11, 4)],
                },
                Division {
                    id: 205,
                    name: "NL Central".to_string(),
                    standings: vec![standing(112, 9, 6)],
                },
            ],
            league_standings: vec![],
            team_ids: vec![],
            date_selector: DateSelector::default(),
            view_mode: ViewMode::ByDivision,
            division_row_indices: HashSet::new(),
            team_page: None,
        };

        state.apply_favorite_team(lookup_team_by_id(147));

        assert_eq!(
            state
                .standings
                .iter()
                .map(|division| division.id)
                .collect::<Vec<_>>(),
            vec![201, 202, 200, 203, 204, 205]
                .into_iter()
                .filter(|id| [200, 201, 205].contains(id))
                .collect::<Vec<_>>()
        );
        assert_eq!(state.get_selected(), 147);
    }
}