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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
use std::collections::{HashMap, HashSet};

use crate::event::{Event, Info, PlayDescription, Player, Team};

pub use self::{Error as GameError, State as GameState};

/// An event with any comments that may correspond to it.
pub type EventWithComments = (Event, Vec<Event>);

#[derive(Clone, Debug, PartialEq)]
/// An error that occurs while processing a game.
pub enum Error {
    /// The event provided is not valid in the current state.
    InvalidEvent(State, Event),
    /// The event before a substitution should always be a play, not something else.
    InvalidEventBeforeSub(Event),
    /// The event before a substitution should always be a play.
    NoEventBeforeSub,
    /// Parsing was already completed, so we cannot parse more events.
    ParsingDone,
    /// Parsing was not done when the user attempted to complete game processing.
    ParsingIncomplete,
    /// A portion of processing is not yet implemented.
    Unimplemented,
}

impl ::std::fmt::Display for Error {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match *self {
            Error::InvalidEvent(ref state, ref event) => write!(
                f,
                "the event {:?} is not valid in the {} state",
                event, state
            ),
            Error::InvalidEventBeforeSub(ref event) => write!(
                f,
                "substitutions must be preceded by a play event; got {:?}",
                event
            ),
            Error::NoEventBeforeSub => write!(f, "substitutions must be preceded by a play event"),
            Error::ParsingDone => write!(f, "parsing already completed"),
            Error::ParsingIncomplete => {
                write!(f, "parsing not fully done before attempted completion")
            }
            Error::Unimplemented => write!(f, "the requested command is not yet implemented"),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
/// A substitution. Denotes what inning and batting team (i.e. bottom or top of inning) and which
/// player was subbed in.
pub struct Substitution {
    /// The inning in which the substitution was made.
    pub inning: u8,
    /// The team that was batting at the time of hte substitution.
    pub batting_team: Team,
    /// The player which was subbed in.
    pub player: Player,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
/// The parsing state of the game.
pub enum State {
    /// Parsing info events.
    Info,
    /// Parsing start events.
    Starters,
    /// Parsing plays.
    Plays,
    /// Parsing end-of-game data.
    Data,
    /// Done parsing.
    Done,
}

impl ::std::fmt::Display for State {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match *self {
            State::Info => write!(f, "metadata parsing"),
            State::Starters => write!(f, "starting roster parsing"),
            State::Plays => write!(f, "play-by-play parsing"),
            State::Data => write!(f, "data parsing"),
            State::Done => write!(f, "finished"),
        }
    }
}

#[derive(Clone, Debug)]
/// An MLB game.
pub struct Game {
    /// The game id.
    pub id: String,
    /// Metadata information about the game.
    pub info: HashMap<Info, String>,
    /// The players that started the game.
    pub starters: HashSet<Player>,
    /// The sequence of plays that occurred in the game, along with comments, if they exist.
    pub plays: Vec<EventWithComments>,
    /// The set of substitutions that happened during the game. This can be used to construct a full
    /// list of who was playing during what parts of the game.
    pub substitutions: Vec<Substitution>,
    /// The set of data events that were recorded after play-by-play information.
    pub data: Vec<Event>,
    pub(crate) state: State,
}

impl PartialEq for Game {
    fn eq(&self, other: &Game) -> bool {
        self.id == other.id
            && self.info == other.info
            && self.starters == other.starters
            && self.plays == other.plays
            && self.substitutions == other.substitutions
            && self.data == other.data
    }
}

impl Eq for Game {}

impl Game {
    /// Instantiate a new game object in the initial state.
    pub fn new<S: Into<String>>(id: S) -> Game {
        Game {
            id: id.into(),
            info: HashMap::new(),
            state: State::Info,
            starters: HashSet::new(),
            plays: vec![],
            substitutions: vec![],
            data: vec![],
        }
    }

    fn process_info_event(&mut self, event: Event) -> Result<(), Error> {
        match event {
            Event::Info { key, data } => {
                self.info.insert(key, data);
                Ok(())
            }
            Event::Start { .. } => {
                // Done with info, so process the event in the starters state.
                self.state = State::Starters;
                self.process_event(event)
            }
            Event::Comment { .. } => Ok(()),
            _ => Err(Error::InvalidEvent(self.state, event.clone())),
        }
    }

    fn process_starter_event(&mut self, event: Event) -> Result<(), Error> {
        match event {
            Event::Start { player } => {
                self.starters.insert(player);
                Ok(())
            }
            // A batting adjustment can happen here if a switch hitter hits leadoff; that counts as
            // part of plays.
            Event::Play { .. } | Event::BattingAdjustment { .. } => {
                // Done with starters, so start play-by-play.
                self.state = State::Plays;
                self.process_event(event)
            }
            Event::Comment { .. } => Ok(()),
            _ => Err(Error::InvalidEvent(self.state, event.clone())),
        }
    }

    fn process_play_event(&mut self, event: Event) -> Result<(), Error> {
        match event {
            Event::Play { .. } => {
                self.plays.push((event, vec![]));
                Ok(())
            }
            Event::BattingAdjustment { .. }
            | Event::PitchingAdjustment { .. }
            | Event::LineupAdjustment { .. } => {
                self.plays.push((event, vec![]));
                Ok(())
            }
            Event::Sub { player } => {
                // We actually get rid of the last play, because it will always be a NoPlay without
                // any pitch count. If not, it's an error and parsing failed anyway.
                let last_evt = self.plays.pop();
                match last_evt {
                    Some(event) => match event.0 {
                        Event::Play {
                            ref inning,
                            ref team,
                            event: ref play_event,
                            ..
                        } => {
                            if play_event.description != PlayDescription::NoPlay {
                                Err(Error::InvalidEventBeforeSub(event.0.clone()))
                            } else {
                                self.substitutions.push(Substitution {
                                    inning: *inning,
                                    batting_team: *team,
                                    player,
                                });
                                Ok(())
                            }
                        }
                        _ => Err(Error::InvalidEventBeforeSub(event.0.clone())),
                    },
                    None => Err(Error::NoEventBeforeSub),
                }
            }
            Event::Comment { .. } => {
                let len = self.plays.len();
                self.plays[len - 1].1.push(event);
                Ok(())
            }
            Event::Data { .. } => {
                // Done with plays, so collect data.
                self.state = State::Data;
                self.process_event(event)
            }
            _ => Err(Error::InvalidEvent(self.state, event.clone())),
        }
    }

    fn process_data_event(&mut self, event: Event) -> Result<(), Error> {
        match event {
            Event::Data { .. } => {
                self.data.push(event);
                Ok(())
            }
            Event::Comment { .. } => Ok(()),
            _ => Err(Error::InvalidEvent(self.state, event.clone())),
        }
    }

    /// Attempt to complete parsing. Only allowed in the data state.
    pub fn finish(&mut self) -> Result<(), Error> {
        if let State::Data = self.state {
            self.state = State::Done;
            Ok(())
        } else {
            Err(Error::ParsingIncomplete)
        }
    }

    /// Process an event in the context of the game.
    pub fn process_event(&mut self, event: Event) -> Result<(), Error> {
        match self.state {
            State::Info => self.process_info_event(event),
            State::Starters => self.process_starter_event(event),
            State::Plays => self.process_play_event(event),
            State::Data => self.process_data_event(event),
            State::Done => Err(Error::ParsingDone),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;
    use std::iter::FromIterator;

    use event::{
        Advance, Base, DataEventType, Event, Hand, Info, Pitch, PlayDescription, PlayEvent, Player,
        Team,
    };

    use super::*;

    #[test]
    fn test_process_info() {
        let mut game = Game::new("foo");

        assert_eq!(
            Ok(()),
            game.process_event(Event::Info {
                key: Info::HomeTeam,
                data: "bar".into()
            })
        );
        assert_eq!(Some(&"bar".into()), game.info.get(&Info::HomeTeam));

        let evt = Event::GameId { id: "blah".into() };
        assert_eq!(
            Err(Error::InvalidEvent(State::Info, evt.clone())),
            game.process_event(evt.clone())
        );

        let player = Player {
            id: "fred103".into(),
            name: "fred".into(),
            team: Team::Home,
            batting_pos: 7,
            fielding_pos: 6,
        };

        assert_eq!(Ok(()), game.process_event(Event::Start { player: player }));
        assert_eq!(State::Starters, game.state);
    }

    #[test]
    fn test_process_starters() {
        let mut game = Game::new("foo");
        let player1 = Player {
            id: "fred103".into(),
            name: "fred".into(),
            team: Team::Home,
            batting_pos: 7,
            fielding_pos: 6,
        };
        let player2 = Player {
            id: "jim104".into(),
            name: "jim".into(),
            team: Team::Visiting,
            batting_pos: 3,
            fielding_pos: 1,
        };

        assert_eq!(
            Ok(()),
            game.process_event(Event::Start {
                player: player1.clone()
            })
        );
        assert_eq!(
            Ok(()),
            game.process_event(Event::Start {
                player: player2.clone()
            })
        );
        assert_eq!(
            HashSet::from_iter(vec![player1.clone(), player2.clone()].into_iter()),
            game.starters
        );

        let evt = Event::Info {
            key: Info::HomeTeam,
            data: "bar".into(),
        };
        assert_eq!(
            Err(Error::InvalidEvent(State::Starters, evt.clone())),
            game.process_event(evt.clone())
        );

        assert_eq!(
            Ok(()),
            game.process_event(Event::Play {
                inning: 2,
                team: Team::Visiting,
                player: "foo".into(),
                count: None,
                pitches: vec![],
                event: PlayEvent {
                    description: PlayDescription::Balk,
                    modifiers: vec![],
                    advances: vec![],
                },
            })
        );
        assert_eq!(State::Plays, game.state);
    }

    #[test]
    fn test_process_plays() {
        let event1 = Event::Play {
            inning: 2,
            team: Team::Visiting,
            player: "foo".into(),
            count: None,
            pitches: vec![],
            event: PlayEvent {
                description: PlayDescription::Balk,
                modifiers: vec![],
                advances: vec![],
            },
        };

        let event_np = Event::Play {
            inning: 2,
            team: Team::Visiting,
            player: "foo".into(),
            count: None,
            pitches: vec![],
            event: PlayEvent {
                description: PlayDescription::NoPlay,
                modifiers: vec![],
                advances: vec![],
            },
        };
        let player = Player {
            id: "fred103".into(),
            name: "fred".into(),
            team: Team::Home,
            batting_pos: 7,
            fielding_pos: 6,
        };
        let event2 = Event::Sub {
            player: player.clone(),
        };
        let event3 = Event::Data {
            data_type: DataEventType::EarnedRuns,
            player: "fred103".into(),
            value: "2".into(),
        };

        let comment = Event::Comment {
            comment: "foo".into(),
        };
        let badj = Event::BattingAdjustment {
            player: "bonib001".into(),
            hand: Hand::Right,
        };
        let padj = Event::PitchingAdjustment {
            player: "harrg001".into(),
            hand: Hand::Left,
        };
        let ladj = Event::LineupAdjustment {
            team: Team::Home,
            position: 7,
        };

        {
            let mut game = Game::new("foo");
            game.state = State::Plays;
            assert_eq!(Ok(()), game.process_event(event1.clone()));
            assert_eq!(vec![(event1.clone(), vec![])], game.plays);
            assert_eq!(Ok(()), game.process_event(comment.clone()));
            assert_eq!(vec![(event1.clone(), vec![comment.clone()])], game.plays);
            assert_eq!(Ok(()), game.process_event(badj.clone()));
            assert_eq!(Ok(()), game.process_event(padj.clone()));
            assert_eq!(Ok(()), game.process_event(ladj.clone()));

            assert_eq!(Ok(()), game.process_event(event_np.clone()));
            assert_eq!(Ok(()), game.process_event(event2.clone()));
            assert_eq!(
                vec![
                    (event1.clone(), vec![comment.clone()]),
                    (badj.clone(), vec![]),
                    (padj.clone(), vec![]),
                    (ladj.clone(), vec![])
                ],
                game.plays
            );

            assert_eq!(
                vec![Substitution {
                    inning: 2,
                    batting_team: Team::Visiting,
                    player: player.clone(),
                }],
                game.substitutions
            );

            assert_eq!(Ok(()), game.process_event(event3));
            assert_eq!(State::Data, game.state);
        }

        {
            let mut game = Game::new("foo");
            game.state = State::Plays;
            assert_eq!(Ok(()), game.process_event(event1.clone()));
            assert_eq!(vec![(event1.clone(), vec![])], game.plays);

            assert_eq!(
                Err(Error::InvalidEventBeforeSub(event1.clone())),
                game.process_event(event2.clone())
            );

            assert_eq!(Ok(()), game.process_event(badj.clone()));
            assert_eq!(
                Err(Error::InvalidEventBeforeSub(badj.clone())),
                game.process_event(event2.clone())
            );
        }

        {
            let mut game = Game::new("foo");
            game.state = State::Plays;

            assert_eq!(
                Err(Error::NoEventBeforeSub),
                game.process_event(event2.clone())
            );
        }

        {
            let mut game = Game::new("foo");
            game.state = State::Plays;
            let info = Event::Info {
                key: Info::HomeTeam,
                data: "bar".into(),
            };

            assert_eq!(
                Err(Error::InvalidEvent(State::Plays, info.clone())),
                game.process_event(info.clone())
            );
        }
    }

    #[test]
    fn test_data() {
        let data = Event::Data {
            data_type: DataEventType::EarnedRuns,
            player: "foo".into(),
            value: "3".into(),
        };
        let info = Event::Info {
            key: Info::HomeTeam,
            data: "bar".into(),
        };

        {
            let mut game = Game::new("foo");
            game.state = State::Data;
            assert_eq!(Ok(()), game.process_event(data.clone()));
            assert_eq!(vec![data.clone()], game.data);
        }

        {
            let mut game = Game::new("foo");
            game.state = State::Data;
            assert_eq!(
                Err(Error::InvalidEvent(State::Data, info.clone())),
                game.process_event(info.clone())
            );
        }
    }

    #[test]
    fn test_done() {
        let mut game = Game::new("foo");
        assert_eq!(Err(Error::ParsingIncomplete), game.finish());

        game.state = State::Data;
        assert_eq!(Ok(()), game.finish());

        assert_eq!(
            Err(Error::ParsingDone),
            game.process_event(Event::Info {
                key: Info::HomeTeam,
                data: "bar".into(),
            })
        );
    }

    #[test]
    fn test_error_printing() {
        let event = Event::Data {
            data_type: DataEventType::EarnedRuns,
            player: "fred103".into(),
            value: "2".into(),
        };
        assert_eq!(
            "the requested command is not yet implemented".to_string(),
            format!("{}", Error::Unimplemented)
        );
        assert_eq!(
            "parsing not fully done before attempted completion".to_string(),
            format!("{}", Error::ParsingIncomplete)
        );
        assert_eq!(
            "parsing already completed".to_string(),
            format!("{}", Error::ParsingDone)
        );
        assert_eq!(
            "substitutions must be preceded by a play event".to_string(),
            format!("{}", Error::NoEventBeforeSub)
        );
        assert_eq!(
            format!(
                "substitutions must be preceded by a play event; got {:?}",
                event
            ),
            format!("{}", Error::InvalidEventBeforeSub(event.clone()))
        );

        assert_eq!(
            format!(
                "the event {:?} is not valid in the metadata parsing state",
                event
            ),
            format!("{}", Error::InvalidEvent(State::Info, event.clone()))
        );
        assert_eq!(
            format!(
                "the event {:?} is not valid in the starting roster parsing state",
                event
            ),
            format!("{}", Error::InvalidEvent(State::Starters, event.clone()))
        );
        assert_eq!(
            format!(
                "the event {:?} is not valid in the play-by-play parsing state",
                event
            ),
            format!("{}", Error::InvalidEvent(State::Plays, event.clone()))
        );
        assert_eq!(
            format!(
                "the event {:?} is not valid in the data parsing state",
                event
            ),
            format!("{}", Error::InvalidEvent(State::Data, event.clone()))
        );
        assert_eq!(
            format!("the event {:?} is not valid in the finished state", event),
            format!("{}", Error::InvalidEvent(State::Done, event.clone()))
        );
    }

    #[test]
    fn test_eq() {
        let info = {
            let mut map = HashMap::new();
            map.insert(Info::Number, "0".into());
            map
        };
        let starters = HashSet::from_iter(
            vec![Player {
                id: "foo".into(),
                name: "Bar".into(),
                team: Team::Visiting,
                batting_pos: 1,
                fielding_pos: 6,
            }]
            .into_iter(),
        );
        let plays = vec![(
            Event::Play {
                inning: 4,
                team: Team::Home,
                player: "meh".into(),
                count: Some((1, 2)),
                pitches: vec![
                    Pitch::CalledStrike,
                    Pitch::CalledStrike,
                    Pitch::BallInPlayBatter,
                ],
                event: PlayEvent {
                    description: PlayDescription::Single(vec![8]),
                    modifiers: vec![],
                    advances: vec![Advance {
                        from: Base::Home,
                        to: Base::Second,
                        success: true,
                        parameters: vec![],
                    }],
                },
            },
            vec![],
        )];
        let data = vec![Event::Data {
            data_type: DataEventType::EarnedRuns,
            player: "foo".into(),
            value: "2".into(),
        }];
        let substitutions = vec![Substitution {
            inning: 4,
            batting_team: Team::Home,
            player: Player {
                id: "buz".into(),
                name: "Bax".into(),
                team: Team::Home,
                batting_pos: 3,
                fielding_pos: 4,
            },
        }];

        let game1 = Game {
            id: "foo".into(),
            info: info.clone(),
            starters: starters.clone(),
            plays: plays.clone(),
            substitutions: substitutions.clone(),
            data: data.clone(),
            state: State::Starters,
        };
        let game2 = Game {
            id: "foo".into(),
            info: info.clone(),
            starters: starters.clone(),
            plays: plays.clone(),
            substitutions: substitutions.clone(),
            data: data.clone(),
            state: State::Plays,
        };

        assert_eq!(game1, game2);
    }
}