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
//! # Games
//!
//! Endpoints available for games

use std::{borrow::Cow, collections::BTreeSet, fmt::Display};

use http::Method;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::{
    categories::CategoryEmbeds, developers::DeveloperId, endpoint::Endpoint, engines::EngineId,
    error::BodyError, gametypes::GameTypeId, genres::GenreId, leaderboards::LeaderboardEmbeds,
    platforms::PlatformId, publishers::PublisherId, regions::RegionId, users::UserId,
    CategoriesSorting, Direction, Pageable, VariablesSorting,
};

/// Embeds available for games
///
/// NOTE: Embeds can be nested. That is not handled by this API.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum GameEmbeds {
    /// Embed all levels defined for the game.
    Levels,
    /// Embed all categories defined for the game.
    Categories,
    /// Embed moderators as full user resources.
    Moderators,
    /// Embed all assigned gametypes.
    Gametypes,
    /// Embed all assigned platforms.
    Platforms,
    /// Embed all assigned regions.
    Regions,
    /// Embed all assigned genres.
    Genres,
    /// Embed all assigned engines.
    Engines,
    /// Embed all assigned developers.
    Developers,
    /// Embed all assigned publishers.
    Publishers,
    /// Embed all variables defined for the game.
    Variables,
}

/// Sorting options for games
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "kebab-case")]
pub enum GamesSorting {
    /// Sorts alphanumerically by the international name (default)
    #[serde(rename = "name.int")]
    NameInternational,
    /// Sorts alphanumerically by the Japanese name
    #[serde(rename = "name.jap")]
    NameJapanese,
    /// Sorts alphanumerically by the abbreviation
    Abbreviation,
    /// Sorts by the release date
    Released,
    /// Sorts by the date the game was added to speedrun.com
    Created,
    /// Sorts by string similarity. *Only available when searching games by
    /// name* (default when searching by name)
    Similarity,
}

// Does this belong here?
/// Sorting options for levels
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "kebab-case")]
pub enum LevelsSorting {
    /// Sorts alphanumerically by the level name
    Name,
    /// Sorts by the order defined by the game moderator (default)
    Pos,
}

// Does this belong here?
/// Type of leaderboard to return.
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "kebab-case")]
pub enum LeaderboardScope {
    /// Only return full-game categories.
    FullGame,
    /// Only return individual levels.
    Levels,
    /// Return all (default)
    All,
}

/// Error type for GameDerivedGamesBuilder
#[derive(Debug, Error)]
pub enum GameDerivedGamesBuilderError {
    /// Uninitialized Field
    #[error("{0} must be initialized")]
    UninitializedField(&'static str),
    /// Error from the inner GamesBuilder
    #[error(transparent)]
    Inner(#[from] GamesBuilderError),
}

/// Represents a game ID
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
pub struct GameId<'a>(Cow<'a, str>);

impl<'a> GameId<'a> {
    /// Create a new [`GameId`]
    pub fn new<T>(id: T) -> Self
    where
        T: Into<Cow<'a, str>>,
    {
        Self(id.into())
    }
}

impl<'a, T> From<T> for GameId<'a>
where
    T: Into<Cow<'a, str>>,
{
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

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

/// Retrievs a lists of all games.
#[derive(Default, Debug, Builder, Serialize, Clone)]
#[builder(default, setter(into, strip_option))]
#[serde(rename_all = "kebab-case")]
pub struct Games<'a> {
    #[doc = r"Performs a fuzzy search across game names and abbreviations."]
    name: Option<Cow<'a, str>>,
    #[doc = r"Perform an exact-match search for this abbreviation."]
    abbreviation: Option<Cow<'a, str>>,
    #[doc = r"Restrict results to games released in the given year."]
    released: Option<i64>,
    #[doc = r"Restrict results to the given game type."]
    gametype: Option<GameTypeId<'a>>,
    #[doc = r"Restrict results to the given platform."]
    platform: Option<PlatformId<'a>>,
    #[doc = r"Restrict results to the given region."]
    region: Option<RegionId<'a>>,
    #[doc = r"Restrict results to the given genre."]
    genre: Option<GenreId<'a>>,
    #[doc = r"Restrict results to the given engine."]
    engine: Option<EngineId<'a>>,
    #[doc = r"Restrict results to the given developer."]
    developer: Option<DeveloperId<'a>>,
    #[doc = r"Restrict results to the given publisher."]
    publisher: Option<PublisherId<'a>>,
    #[doc = r"Only return games moderated by the given user."]
    moderator: Option<UserId<'a>>,
    #[doc = r"Enable bulk access."]
    #[serde(rename = "_bulk")]
    bulk: Option<bool>,
    #[doc = r"Sorting options for results."]
    orderby: Option<GamesSorting>,
    #[doc = r"Sort direction."]
    direction: Option<Direction>,
    #[builder(setter(name = "_embed"), private)]
    #[serde(serialize_with = "super::utils::serialize_as_csv")]
    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
    embed: BTreeSet<GameEmbeds>,
}

/// Retrieves a single game, identified by ID.
#[derive(Debug, Builder, Clone)]
#[builder(setter(into, strip_option))]
pub struct Game<'a> {
    #[doc = r"`ID` of the game."]
    id: GameId<'a>,
}

/// Retrieve all categories for the given game.
#[derive(Debug, Builder, Serialize, Clone)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "kebab-case")]
pub struct GameCategories<'a> {
    #[doc = r"`ID` of the game to retrieve categories for."]
    #[serde(skip)]
    id: GameId<'a>,
    #[doc = r"Filter miscellaneous categories."]
    #[builder(default)]
    miscellaneous: Option<bool>,
    #[doc = r"Sorting options for results."]
    #[builder(default)]
    orderby: Option<CategoriesSorting>,
    #[doc = r"Sort direction."]
    #[builder(default)]
    direction: Option<Direction>,
    #[builder(setter(name = "_embed"), private, default)]
    #[serde(serialize_with = "super::utils::serialize_as_csv")]
    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
    embed: BTreeSet<CategoryEmbeds>,
}

impl<'a> GameCategoriesBuilder<'a> {
    /// Add an embedded resource to this result
    pub fn embed(&mut self, embed: CategoryEmbeds) -> &mut Self {
        self.embed.get_or_insert_with(BTreeSet::new).insert(embed);
        self
    }

    /// Add multiple embedded resources to this result
    pub fn embeds<I>(&mut self, iter: I) -> &mut Self
    where
        I: Iterator<Item = CategoryEmbeds>,
    {
        self.embed.get_or_insert_with(BTreeSet::new).extend(iter);
        self
    }
}

/// Retrieves all levels for the given game.
#[derive(Debug, Builder, Serialize, Clone)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "kebab-case")]
pub struct GameLevels<'a> {
    #[doc = r"`ID` of the game to retrieve levels for."]
    #[serde(skip)]
    id: GameId<'a>,
    #[doc = r"Sorting options for results."]
    #[builder(default)]
    orderby: Option<LevelsSorting>,
    #[doc = r"Sort direction."]
    #[builder(default)]
    direction: Option<Direction>,
}

/// Retrieves all variables for the given game.
#[derive(Debug, Builder, Serialize, Clone)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "kebab-case")]
pub struct GameVariables<'a> {
    #[doc = r"`ID` of the game to retrieve variables for."]
    #[serde(skip)]
    id: GameId<'a>,
    #[doc = r"Sorting options for results."]
    #[builder(default)]
    orderby: Option<VariablesSorting>,
    #[doc = r"Sort direction."]
    #[builder(default)]
    direction: Option<Direction>,
}

/// Builder for [`GameDerivedGames`].
#[derive(Default, Clone)]
pub struct GameDerivedGamesBuilder<'a> {
    id: Option<GameId<'a>>,
    inner: GamesBuilder<'a>,
}

/// Retrieves all games that have the given game as their base game.
#[derive(Debug, Clone)]
pub struct GameDerivedGames<'a> {
    id: GameId<'a>,
    inner: Games<'a>,
}

/// Retrieves all records (top 3 places) for every (category/level) combonation
/// of the given game.
#[derive(Debug, Builder, Serialize, Clone)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "kebab-case")]
pub struct GameRecords<'a> {
    #[doc = r"`ID` of the game to retrieve records for."]
    id: GameId<'a>,
    #[doc = r"Return the `top` *places* (this can result in more than `top` runs!). Defaults to 3."]
    #[builder(default)]
    top: Option<i64>,
    #[doc = r"When set to [`LeaderboardScope::FullGame`], only full-game categories will be included. When set to [`LeaderboardScope::Levels`] only individual levels are returned. Defaults to [`LeaderboardScope::All`]."]
    #[builder(default)]
    scope: Option<LeaderboardScope>,
    #[doc = r"When `false`, miscellaneous categories will not be included in the results."]
    #[builder(default)]
    miscellaneous: Option<bool>,
    #[doc = r"When `true`, empty leaderboards will not be included in the results."]
    #[builder(default)]
    skip_empty: Option<bool>,
    #[builder(setter(name = "_embed"), private, default)]
    #[serde(serialize_with = "super::utils::serialize_as_csv")]
    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
    embed: BTreeSet<LeaderboardEmbeds>,
}

impl<'a> Games<'a> {
    /// Create a builder for this endpoint.
    pub fn builder() -> GamesBuilder<'a> {
        GamesBuilder::default()
    }
}

impl<'a> GamesBuilder<'a> {
    /// Add an embedded resource to this result.
    pub fn embed(&mut self, embed: GameEmbeds) -> &mut Self {
        self.embed.get_or_insert_with(BTreeSet::new).insert(embed);
        self
    }

    /// Add multiple embedded resources to this result.
    pub fn embeds<I>(&mut self, iter: I) -> &mut Self
    where
        I: Iterator<Item = GameEmbeds>,
    {
        self.embed.get_or_insert_with(BTreeSet::new).extend(iter);
        self
    }
}

impl<'a> Game<'a> {
    /// Create a builder for this endpoint.
    pub fn builder() -> GameBuilder<'a> {
        GameBuilder::default()
    }
}

impl<'a> GameCategories<'a> {
    /// Create a builder for this endpoint.
    pub fn builder() -> GameCategoriesBuilder<'a> {
        GameCategoriesBuilder::default()
    }
}

impl<'a> GameLevels<'a> {
    /// Create a builder for this endpoint.
    pub fn builder() -> GameLevelsBuilder<'a> {
        GameLevelsBuilder::default()
    }
}

impl<'a> GameVariables<'a> {
    /// Create a builder for this endpoint.
    pub fn builder() -> GameVariablesBuilder<'a> {
        GameVariablesBuilder::default()
    }
}

impl<'a> GameDerivedGamesBuilder<'a> {
    /// `ID` of the base game to retrieve games for.
    pub fn id<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<GameId<'a>>,
    {
        self.id = Some(value.into());
        self
    }

    /// Performs a fuzzy search across game names and abbreviations.
    pub fn name<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<Cow<'a, str>>,
    {
        self.inner.name(value);
        self
    }

    /// Perform an exact-match search for this abbreviation.
    pub fn abbreviation<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<Cow<'a, str>>,
    {
        self.inner.abbreviation(value);
        self
    }

    /// Restrict results to games released in the given year.
    pub fn released<T>(&mut self, value: T) -> &mut Self
    where
        T: Into<i64>,
    {
        self.inner.released(value);
        self
    }

    /// Restrict results to the given game type.
    pub fn gametype<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<GameTypeId<'a>>,
    {
        self.inner.gametype(value);
        self
    }

    /// Restrict results to the given platform.
    pub fn platform<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<PlatformId<'a>>,
    {
        self.inner.platform(value);
        self
    }

    /// Restrict results to the given region.
    pub fn region<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<RegionId<'a>>,
    {
        self.inner.region(value);
        self
    }

    /// Restrict results to the given genre.
    pub fn genre<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<GenreId<'a>>,
    {
        self.inner.genre(value);
        self
    }

    /// Restrict results to the given engine.
    pub fn engine<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<EngineId<'a>>,
    {
        self.inner.engine(value);
        self
    }

    /// Restrict results to the given developer.
    pub fn developer<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<DeveloperId<'a>>,
    {
        self.inner.developer(value);
        self
    }

    /// Restrict results to the given publisher.
    pub fn publisher<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<PublisherId<'a>>,
    {
        self.inner.publisher(value);
        self
    }

    /// Only return games moderated by the given user.
    pub fn moderator<S>(&mut self, value: S) -> &mut Self
    where
        S: Into<UserId<'a>>,
    {
        self.inner.moderator(value);
        self
    }

    /// Enable bulk access.
    pub fn bulk<T>(&mut self, value: T) -> &mut Self
    where
        T: Into<bool>,
    {
        self.inner.bulk(value);
        self
    }

    /// Sorting options for results.
    pub fn orderby<V>(&mut self, value: V) -> &mut Self
    where
        V: Into<GamesSorting>,
    {
        self.inner.orderby(value);
        self
    }

    /// Sort direction.
    pub fn direction<V>(&mut self, value: V) -> &mut Self
    where
        V: Into<Direction>,
    {
        self.inner.direction(value);
        self
    }

    /// Builds a new [`GameDerivedGames`].
    ///
    /// # Errors
    ///
    /// If a required field has not been initialized.
    pub fn build(&self) -> Result<GameDerivedGames<'a>, GameDerivedGamesBuilderError> {
        let inner = self.inner.build()?;
        Ok(GameDerivedGames {
            id: self
                .id
                .as_ref()
                .cloned()
                .ok_or(GameDerivedGamesBuilderError::UninitializedField("id"))?,
            inner,
        })
    }
}

impl<'a> GameDerivedGames<'a> {
    /// Create a builder for this endpoint.
    pub fn builder() -> GameDerivedGamesBuilder<'a> {
        GameDerivedGamesBuilder::default()
    }
}

impl<'a> GameRecords<'a> {
    /// Create a builder for this endpoint.
    pub fn builder() -> GameRecordsBuilder<'a> {
        GameRecordsBuilder::default()
    }
}

impl<'a> GameRecordsBuilder<'a> {
    /// Add an embedded resource to this result.
    pub fn embed(&mut self, embed: LeaderboardEmbeds) -> &mut Self {
        self.embed.get_or_insert_with(BTreeSet::new).insert(embed);
        self
    }

    /// Add multiple embedded resources to this result.
    pub fn embeds<I>(&mut self, iter: I) -> &mut Self
    where
        I: Iterator<Item = LeaderboardEmbeds>,
    {
        self.embed.get_or_insert_with(BTreeSet::new).extend(iter);
        self
    }
}

impl GameEmbeds {
    fn as_str(&self) -> &'static str {
        match self {
            GameEmbeds::Levels => "levels",
            GameEmbeds::Categories => "categories",
            GameEmbeds::Moderators => "moderators",
            GameEmbeds::Gametypes => "gametypes",
            GameEmbeds::Platforms => "platforms",
            GameEmbeds::Regions => "regions",
            GameEmbeds::Genres => "genres",
            GameEmbeds::Engines => "engines",
            GameEmbeds::Developers => "developers",
            GameEmbeds::Publishers => "publishers",
            GameEmbeds::Variables => "variables",
        }
    }
}

impl Default for LevelsSorting {
    fn default() -> Self {
        Self::Pos
    }
}

impl Endpoint for Games<'_> {
    fn method(&self) -> http::Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        "games".into()
    }

    fn query_parameters(&self) -> Result<Cow<'static, str>, BodyError> {
        Ok(serde_urlencoded::to_string(self)?.into())
    }
}

impl Endpoint for Game<'_> {
    fn method(&self) -> Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("/games/{}", self.id).into()
    }
}

impl Endpoint for GameCategories<'_> {
    fn method(&self) -> Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("/games/{}/categories", self.id).into()
    }

    fn query_parameters(&self) -> Result<Cow<'static, str>, BodyError> {
        Ok(serde_urlencoded::to_string(self)?.into())
    }
}

impl Endpoint for GameLevels<'_> {
    fn method(&self) -> Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("/games/{}/levels", self.id).into()
    }

    fn query_parameters(&self) -> Result<Cow<'static, str>, BodyError> {
        Ok(serde_urlencoded::to_string(self)?.into())
    }
}

impl Endpoint for GameVariables<'_> {
    fn method(&self) -> Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("/games/{}/variables", self.id).into()
    }

    fn query_parameters(&self) -> Result<Cow<'static, str>, BodyError> {
        Ok(serde_urlencoded::to_string(self)?.into())
    }
}

impl Endpoint for GameDerivedGames<'_> {
    fn method(&self) -> Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("/games/{}/derived-games", self.id).into()
    }

    fn query_parameters(&self) -> Result<Cow<'static, str>, BodyError> {
        Ok(serde_urlencoded::to_string(&self.inner)?.into())
    }
}

impl Endpoint for GameRecords<'_> {
    fn method(&self) -> Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("/games/{}/records", self.id).into()
    }

    fn query_parameters(&self) -> Result<Cow<'static, str>, BodyError> {
        Ok(serde_urlencoded::to_string(self)?.into())
    }
}

impl From<&GameEmbeds> for &'static str {
    fn from(value: &GameEmbeds) -> Self {
        value.as_str()
    }
}

impl Pageable for GameDerivedGames<'_> {}

impl Pageable for Games<'_> {}

impl Pageable for GameRecords<'_> {}