nhl_api 0.7.1

An NHL stats and scores API client
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
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
use chrono::{Datelike, NaiveDate};
use std::fmt;
use std::str::FromStr;

/// A date wrapper for NHL API calls that can be "now" or a specific date
#[derive(Debug, Clone, PartialEq, Default)]
pub enum GameDate {
    /// Use the current date
    #[default]
    Now,
    /// Use a specific date
    Date(NaiveDate),
}

impl GameDate {
    /// Create a GameDate from today's date
    pub fn today() -> Self {
        Self::Date(chrono::Local::now().date_naive())
    }

    /// Create a GameDate from a specific date
    pub fn from_date(date: NaiveDate) -> Self {
        Self::Date(date)
    }

    /// Create a GameDate from year, month, day
    pub fn from_ymd(year: i32, month: u32, day: u32) -> Option<Self> {
        NaiveDate::from_ymd_opt(year, month, day).map(Self::Date)
    }

    /// Convert to API string format (YYYY-MM-DD or "now")
    pub fn to_api_string(&self) -> String {
        match self {
            Self::Now => "now".to_string(),
            Self::Date(date) => date.format("%Y-%m-%d").to_string(),
        }
    }

    /// Convert to a concrete date (resolves "now" to today's date)
    fn as_date(&self) -> NaiveDate {
        match self {
            Self::Now => chrono::Local::now().date_naive(),
            Self::Date(date) => *date,
        }
    }

    /// Add or subtract days from the date
    pub fn add_days(&self, days: i64) -> Self {
        Self::Date(self.as_date() + chrono::Duration::days(days))
    }
}

impl FromStr for GameDate {
    type Err = chrono::ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "now" {
            Ok(Self::Now)
        } else {
            NaiveDate::parse_from_str(s, "%Y-%m-%d").map(Self::Date)
        }
    }
}

impl From<NaiveDate> for GameDate {
    fn from(date: NaiveDate) -> Self {
        Self::Date(date)
    }
}

impl fmt::Display for GameDate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_api_string())
    }
}

/// A season identifier (e.g., 20232024 for the 2023-2024 season)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Season {
    /// The starting year of the season
    pub start_year: u16,
}

impl Season {
    /// Create a new season from the starting year
    pub fn new(start_year: u16) -> Self {
        Self { start_year }
    }

    /// Create a season from start and end years (e.g., 2023, 2024)
    pub fn from_years(start_year: u16, end_year: u16) -> Self {
        debug_assert_eq!(
            end_year,
            start_year + 1,
            "End year should be start year + 1"
        );
        Self { start_year }
    }

    /// Get the end year of the season
    pub fn end_year(&self) -> u16 {
        self.start_year + 1
    }

    /// Convert to API string format (YYYYYYYY)
    #[allow(clippy::wrong_self_convention)]
    pub fn to_api_string(&self) -> String {
        format!("{}{}", self.start_year, self.end_year())
    }

    /// Parse from API string format (YYYYYYYY)
    pub fn parse(s: &str) -> Option<Self> {
        if s.len() != 8 {
            return None;
        }
        let start_year: u16 = s[0..4].parse().ok()?;
        let end_year: u16 = s[4..8].parse().ok()?;
        if end_year != start_year + 1 {
            return None;
        }
        Some(Self { start_year })
    }

    /// Get the current NHL season based on the current date
    /// NHL seasons typically start in October
    pub fn current() -> Self {
        let now = chrono::Local::now().date_naive();
        let year = now.year() as u16;
        // If it's before October, we're still in the previous season
        if now.month() < 10 {
            Self::new(year - 1)
        } else {
            Self::new(year)
        }
    }
}

impl fmt::Display for Season {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_api_string())
    }
}

impl From<i32> for Season {
    /// Create a Season from an i32 season ID (e.g., 20232024)
    fn from(season_id: i32) -> Self {
        let start_year = (season_id / 10000) as u16;
        Self { start_year }
    }
}

impl From<i64> for Season {
    /// Create a Season from an i64 season ID (e.g., 20232024)
    fn from(season_id: i64) -> Self {
        let start_year = (season_id / 10000) as u16;
        Self { start_year }
    }
}

impl From<u16> for Season {
    /// Create a Season from a u16 starting year (e.g., 2023)
    fn from(start_year: u16) -> Self {
        Self::new(start_year)
    }
}

impl FromStr for Season {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s).ok_or(())
    }
}

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

    #[test]
    fn test_game_date_now() {
        let date = GameDate::Now;
        assert_eq!(date.to_api_string(), "now");
    }

    #[test]
    fn test_game_date_specific() {
        let date = GameDate::from_ymd(2024, 10, 19).unwrap();
        assert_eq!(date.to_api_string(), "2024-10-19");
    }

    #[test]
    fn test_game_date_from_str() {
        let date: GameDate = "2024-10-19".parse().unwrap();
        assert_eq!(date.to_api_string(), "2024-10-19");

        let now: GameDate = "now".parse().unwrap();
        assert_eq!(now, GameDate::Now);
    }

    #[test]
    fn test_game_date_from_str_trait() {
        // Test using the FromStr trait via .parse()
        let date: GameDate = "2024-10-19".parse().unwrap();
        assert_eq!(date.to_api_string(), "2024-10-19");

        let now: GameDate = "now".parse().unwrap();
        assert_eq!(now, GameDate::Now);
        assert_eq!(now.to_api_string(), "now");
    }

    #[test]
    fn test_game_date_today() {
        let date = GameDate::today();
        match date {
            GameDate::Date(_) => {} // Success
            GameDate::Now => panic!("today() should return a specific date"),
        }
    }

    #[test]
    fn test_season_to_string() {
        let season = Season::new(2023);
        assert_eq!(season.to_api_string(), "20232024");
        assert_eq!(season.end_year(), 2024);
    }

    #[test]
    fn test_season_from_str() {
        let season = Season::from_str("20232024").unwrap();
        assert_eq!(season.start_year, 2023);
        assert_eq!(season.end_year(), 2024);

        // Invalid formats should return Err
        assert!(Season::from_str("2023").is_err());
        assert!(Season::from_str("20232025").is_err()); // Not consecutive years
    }

    #[test]
    fn test_season_from_years() {
        let season = Season::from_years(2023, 2024);
        assert_eq!(season.start_year, 2023);
        assert_eq!(season.to_api_string(), "20232024");
    }

    #[test]
    fn test_season_current() {
        let season = Season::current();
        // Just verify it returns a valid season
        assert!(season.start_year >= 2024);
    }

    #[test]
    fn test_game_date_from_date() {
        let naive_date = NaiveDate::from_ymd_opt(2024, 3, 15).unwrap();
        let game_date = GameDate::from_date(naive_date);
        assert_eq!(game_date.to_api_string(), "2024-03-15");
    }

    #[test]
    fn test_game_date_default() {
        let default_date = GameDate::default();
        assert_eq!(default_date, GameDate::Now);
        assert_eq!(default_date.to_api_string(), "now");
    }

    #[test]
    fn test_game_date_from_naive_date() {
        let naive_date = NaiveDate::from_ymd_opt(2024, 12, 25).unwrap();
        let game_date: GameDate = naive_date.into();
        assert_eq!(game_date.to_api_string(), "2024-12-25");
    }

    #[test]
    fn test_game_date_display() {
        let now = GameDate::Now;
        assert_eq!(format!("{}", now), "now");

        // Use different month and day values to verify correct ordering (YYYY-MM-DD)
        let date = GameDate::from_ymd(2024, 3, 15).unwrap();
        assert_eq!(format!("{}", date), "2024-03-15");
    }

    #[test]
    fn test_game_date_from_ymd_invalid() {
        // Invalid month
        assert!(GameDate::from_ymd(2024, 13, 1).is_none());

        // Invalid day
        assert!(GameDate::from_ymd(2024, 2, 30).is_none());

        // Invalid day for month
        assert!(GameDate::from_ymd(2024, 4, 31).is_none());

        // Day 0
        assert!(GameDate::from_ymd(2024, 1, 0).is_none());

        // Month 0
        assert!(GameDate::from_ymd(2024, 0, 1).is_none());
    }

    #[test]
    fn test_game_date_from_str_invalid() {
        // Invalid format
        assert!("2024/10/19".parse::<GameDate>().is_err());
        assert!("10-19-2024".parse::<GameDate>().is_err());
        assert!("2024-10".parse::<GameDate>().is_err());
        assert!("".parse::<GameDate>().is_err());
        assert!("not-a-date".parse::<GameDate>().is_err());

        // Invalid date values
        assert!("2024-13-01".parse::<GameDate>().is_err());
        assert!("2024-02-30".parse::<GameDate>().is_err());
    }

    #[test]
    fn test_game_date_equality() {
        let date1 = GameDate::from_ymd(2024, 10, 19).unwrap();
        let date2 = GameDate::from_ymd(2024, 10, 19).unwrap();
        let date3 = GameDate::from_ymd(2024, 10, 20).unwrap();

        assert_eq!(date1, date2);
        assert_ne!(date1, date3);
        assert_ne!(date1, GameDate::Now);

        let now1 = GameDate::Now;
        let now2 = GameDate::Now;
        assert_eq!(now1, now2);
    }

    #[test]
    fn test_season_display() {
        let season = Season::new(2023);
        assert_eq!(format!("{}", season), "20232024");

        let season2 = Season::new(2019);
        assert_eq!(format!("{}", season2), "20192020");
    }

    #[test]
    fn test_season_from_str_edge_cases() {
        // Empty string
        assert!(Season::from_str("").is_err());

        // Too short
        assert!(Season::from_str("2023").is_err());
        assert!(Season::from_str("202324").is_err());

        // Too long
        assert!(Season::from_str("202320240").is_err());

        // Non-numeric characters
        assert!(Season::from_str("abcd efgh").is_err());
        assert!(Season::from_str("2023abcd").is_err());

        // Years not consecutive
        assert!(Season::from_str("20232025").is_err());
        assert!(Season::from_str("20232023").is_err());
        assert!(Season::from_str("20242023").is_err());

        // Valid edge cases
        let season = Season::from_str("19992000").unwrap();
        assert_eq!(season.start_year, 1999);

        let season = Season::from_str("20502051").unwrap();
        assert_eq!(season.start_year, 2050);
    }

    #[test]
    fn test_add_days_with_specific_date() {
        let date = GameDate::from_ymd(2024, 10, 19).unwrap();

        // Add positive days
        let future = date.add_days(5);
        assert_eq!(future.to_api_string(), "2024-10-24");

        // Add negative days (subtract)
        let past = date.add_days(-5);
        assert_eq!(past.to_api_string(), "2024-10-14");

        // Add zero days
        let same = date.add_days(0);
        assert_eq!(same.to_api_string(), "2024-10-19");
    }

    #[test]
    fn test_add_days_across_month_boundary() {
        let date = GameDate::from_ymd(2024, 10, 30).unwrap();

        // Cross into next month
        let next_month = date.add_days(5);
        assert_eq!(next_month.to_api_string(), "2024-11-04");

        // Cross into previous month
        let date2 = GameDate::from_ymd(2024, 11, 3).unwrap();
        let prev_month = date2.add_days(-5);
        assert_eq!(prev_month.to_api_string(), "2024-10-29");
    }

    #[test]
    fn test_add_days_across_year_boundary() {
        let date = GameDate::from_ymd(2024, 12, 30).unwrap();

        // Cross into next year
        let next_year = date.add_days(5);
        assert_eq!(next_year.to_api_string(), "2025-01-04");

        // Cross into previous year
        let date2 = GameDate::from_ymd(2025, 1, 3).unwrap();
        let prev_year = date2.add_days(-5);
        assert_eq!(prev_year.to_api_string(), "2024-12-29");
    }

    #[test]
    fn test_add_days_leap_year() {
        // 2024 is a leap year
        let date = GameDate::from_ymd(2024, 2, 28).unwrap();

        // February 29 exists in 2024
        let leap_day = date.add_days(1);
        assert_eq!(leap_day.to_api_string(), "2024-02-29");

        let march_1 = date.add_days(2);
        assert_eq!(march_1.to_api_string(), "2024-03-01");

        // 2023 is not a leap year
        let date_2023 = GameDate::from_ymd(2023, 2, 28).unwrap();
        let march_1_2023 = date_2023.add_days(1);
        assert_eq!(march_1_2023.to_api_string(), "2023-03-01");
    }

    #[test]
    fn test_add_days_with_now() {
        // Note: This test is time-dependent but should work
        // We're just verifying that "now" gets converted to a date
        let now = GameDate::Now;
        let future = now.add_days(7);

        // Should return a Date variant, not Now
        match future {
            GameDate::Date(_) => {} // Success
            GameDate::Now => panic!("add_days(7) on Now should return a specific date"),
        }

        // Verify the format is a date string
        let future_str = future.to_api_string();
        assert_ne!(future_str, "now");
        assert!(future_str.contains("-")); // Should be YYYY-MM-DD format
    }

    #[test]
    fn test_add_days_large_values() {
        let date = GameDate::from_ymd(2024, 1, 1).unwrap();

        // Add a full year (2024 is a leap year with 366 days)
        let next_year = date.add_days(366);
        assert_eq!(next_year.to_api_string(), "2025-01-01");

        // Subtract a full year (365 days takes us back to Jan 1, 2023)
        let prev_year = date.add_days(-365);
        assert_eq!(prev_year.to_api_string(), "2023-01-01");

        // Add multiple years (365 * 5 = 1825 days from 2024-01-01)
        // 2024 has 366 days (leap year), others have 365
        // Result is 2028-12-30
        let far_future = date.add_days(365 * 5);
        assert_eq!(far_future.to_api_string(), "2028-12-30");
    }

    #[test]
    fn test_add_days_chaining() {
        let date = GameDate::from_ymd(2024, 10, 15).unwrap();

        // Chain multiple add_days calls
        let result = date.add_days(5).add_days(3).add_days(-2);
        assert_eq!(result.to_api_string(), "2024-10-21");

        // Should be equivalent to adding all at once
        let direct = date.add_days(6);
        assert_eq!(result.to_api_string(), direct.to_api_string());
    }

    #[test]
    fn test_season_from_i32() {
        // Standard season ID
        let season: Season = 20232024_i32.into();
        assert_eq!(season.start_year, 2023);
        assert_eq!(season.end_year(), 2024);

        // Earlier season
        let season: Season = 19992000_i32.into();
        assert_eq!(season.start_year, 1999);
        assert_eq!(season.end_year(), 2000);

        // Very early season
        let season: Season = 19171918_i32.into();
        assert_eq!(season.start_year, 1917);

        // Future season
        let season: Season = 20502051_i32.into();
        assert_eq!(season.start_year, 2050);
    }

    #[test]
    fn test_season_from_i64() {
        // Standard season ID
        let season: Season = 20232024_i64.into();
        assert_eq!(season.start_year, 2023);
        assert_eq!(season.end_year(), 2024);

        // Earlier season
        let season: Season = 19992000_i64.into();
        assert_eq!(season.start_year, 1999);

        // Test that i64 handles the same values correctly
        let season_i32: Season = 20232024_i32.into();
        let season_i64: Season = 20232024_i64.into();
        assert_eq!(season_i32, season_i64);
    }

    #[test]
    fn test_season_from_u16() {
        // Standard starting year
        let season: Season = 2023_u16.into();
        assert_eq!(season.start_year, 2023);
        assert_eq!(season.end_year(), 2024);
        assert_eq!(season.to_api_string(), "20232024");

        // Earlier year
        let season: Season = 1999_u16.into();
        assert_eq!(season.start_year, 1999);

        // Verify it's equivalent to Season::new
        let from_new = Season::new(2023);
        let from_u16: Season = 2023_u16.into();
        assert_eq!(from_new, from_u16);
    }

    #[test]
    fn test_season_hash() {
        use std::collections::HashSet;

        let season1 = Season::new(2023);
        let season2 = Season::new(2023);
        let season3 = Season::new(2024);

        let mut set = HashSet::new();
        set.insert(season1);
        set.insert(season2); // Should not add duplicate
        set.insert(season3);

        assert_eq!(set.len(), 2);
        assert!(set.contains(&Season::new(2023)));
        assert!(set.contains(&Season::new(2024)));
        assert!(!set.contains(&Season::new(2022)));
    }

    #[test]
    fn test_season_copy() {
        let season1 = Season::new(2023);
        let season2 = season1; // Copy, not move

        // Both should still be usable
        assert_eq!(season1.start_year, 2023);
        assert_eq!(season2.start_year, 2023);
        assert_eq!(season1, season2);
    }

    #[test]
    fn test_season_eq() {
        let season1 = Season::new(2023);
        let season2 = Season::new(2023);
        let season3 = Season::new(2024);

        // Test Eq (reflexive, symmetric, transitive)
        assert_eq!(season1, season1); // Reflexive
        assert_eq!(season1, season2); // Symmetric
        assert_eq!(season2, season1);
        assert_ne!(season1, season3);
        assert_ne!(season3, season1);
    }

    #[test]
    fn test_season_parse_non_numeric() {
        // Non-numeric in first half
        assert!(Season::parse("abcd2024").is_none());

        // Non-numeric in second half
        assert!(Season::parse("2023abcd").is_none());

        // Special characters
        assert!(Season::parse("2023-024").is_none());
        assert!(Season::parse("2023/024").is_none());

        // Spaces
        assert!(Season::parse("2023 024").is_none());
        assert!(Season::parse(" 2032024").is_none());
    }

    #[test]
    fn test_game_date_clone() {
        let date = GameDate::from_ymd(2024, 10, 19).unwrap();
        let cloned = date.clone();

        assert_eq!(date, cloned);
        assert_eq!(date.to_api_string(), cloned.to_api_string());

        let now = GameDate::Now;
        let now_cloned = now.clone();
        assert_eq!(now, now_cloned);
    }

    #[test]
    fn test_game_date_debug() {
        let date = GameDate::from_ymd(2024, 10, 19).unwrap();
        let debug_str = format!("{:?}", date);
        assert!(debug_str.contains("Date"));
        assert!(debug_str.contains("2024"));

        let now = GameDate::Now;
        let debug_str = format!("{:?}", now);
        assert_eq!(debug_str, "Now");
    }

    #[test]
    fn test_season_debug() {
        let season = Season::new(2023);
        let debug_str = format!("{:?}", season);
        assert!(debug_str.contains("Season"));
        assert!(debug_str.contains("2023"));
    }

    #[test]
    fn test_season_clone() {
        let season = Season::new(2023);
        let cloned = season.clone();

        assert_eq!(season, cloned);
        assert_eq!(season.start_year, cloned.start_year);
    }

    #[test]
    fn test_season_parse_boundary_years() {
        // Year 0000 (invalid but parseable)
        assert!(Season::parse("00000001").is_some());

        // Maximum u16 boundary (9999 -> 10000 would overflow end_year check)
        // 99999999 would have start 9999, end 9999, which is not +1
        assert!(Season::parse("99999999").is_none());

        // Valid high year
        let season = Season::parse("99989999").unwrap();
        assert_eq!(season.start_year, 9998);
    }

    #[test]
    fn test_game_date_as_date_now_variant() {
        // This tests the as_date method indirectly through add_days
        // when starting from Now
        let now = GameDate::Now;
        let tomorrow = now.add_days(1);
        let yesterday_from_tomorrow = tomorrow.add_days(-1);

        // The dates should match (both resolve to "today")
        let today = GameDate::today();
        assert_eq!(
            yesterday_from_tomorrow.to_api_string(),
            today.to_api_string()
        );
    }

    #[test]
    fn test_season_from_years_equivalence() {
        // Verify from_years produces same result as new
        let from_years = Season::from_years(2023, 2024);
        let from_new = Season::new(2023);

        assert_eq!(from_years, from_new);
        assert_eq!(from_years.start_year, from_new.start_year);
        assert_eq!(from_years.end_year(), from_new.end_year());
    }
}