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
//! # Series
//!
//! Endpoints available for series.
use std::{borrow::Cow, collections::BTreeSet, fmt::Display};

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

use super::{
    developers::DeveloperId,
    endpoint::Endpoint,
    engines::EngineId,
    games::{Games, GamesBuilder, GamesBuilderError, GamesSorting},
    gametypes::GameTypeId,
    genres::GenreId,
    platforms::PlatformId,
    publishers::PublisherId,
    regions::RegionId,
    users::UserId,
    Direction, Pageable,
};

/// Embeds available for series.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum SeriesEmbeds {
    /// Embed moderators a full user resources.
    Moderators,
}

/// Sorting options for game series
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "kebab-case")]
pub enum SeriesSorting {
    /// 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 date the series was added to speedrun.com
    Created,
}

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

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

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

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

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

/// Retrieves a list of all series
#[derive(Default, Debug, Builder, Serialize, Clone)]
#[builder(default, setter(into, strip_option))]
#[serde(rename_all = "kebab-case")]
pub struct ListSeries<'a> {
    #[doc = r"When given, performs a fuzzy search across all series names and abbreviations."]
    name: Option<Cow<'a, str>>,
    #[doc = r"When given, performs an exact-match search for `abbreviation`."]
    abbreviation: Option<Cow<'a, str>>,
    #[doc = r"When given, only return series moderated by [`UserId`]"]
    moderator: Option<UserId<'a>>,
    #[doc = r"Sorting options for results."]
    orderby: Option<SeriesSorting>,
    #[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<SeriesEmbeds>,
}

/// Retrieves a single series
#[derive(Debug, Builder, Clone)]
#[builder(setter(into, strip_option))]
pub struct Series<'a> {
    #[doc = r"Series ID or abbreviation"]
    id: SeriesId<'a>,
}

/// Retrieves all games for a given series
#[derive(Debug, Clone)]
pub struct SeriesGames<'a> {
    id: SeriesId<'a>,
    inner: Games<'a>,
}

/// Builder for [`SeriesGames`]
#[derive(Default, Clone)]
pub struct SeriesGamesBuilder<'a> {
    /// Series ID or abbreviation
    id: Option<SeriesId<'a>>,
    inner: GamesBuilder<'a>,
}

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

impl<'a> ListSeriesBuilder<'a> {
    /// Add an embedded resource to this result
    pub fn embed(&mut self, embed: SeriesEmbeds) -> &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 = SeriesEmbeds>,
    {
        self.embed.get_or_insert_with(BTreeSet::new).extend(iter);
        self
    }
}

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

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

impl<'a> SeriesGamesBuilder<'a> {
    /// Create a new [`SeriesGamesBuilder`]
    pub fn new() -> Self {
        Self::default()
    }

    /// Series ID or abbreviation
    pub fn id<S>(&mut self, id: S) -> &mut Self
    where
        S: Into<SeriesId<'a>>,
    {
        self.id = Some(id.into());
        self
    }

    #[doc = r"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
    }

    #[doc = r"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
    }

    #[doc = r"Restrict results to games released in the given year."]
    pub fn released(&mut self, value: i64) -> &mut Self {
        self.inner.released(value);
        self
    }

    #[doc = r"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
    }

    #[doc = r"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
    }

    #[doc = r"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
    }

    #[doc = r"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
    }

    #[doc = r"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
    }

    #[doc = r"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
    }

    #[doc = r"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
    }

    #[doc = r"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
    }

    #[doc = r"Enable bulk access."]
    pub fn bulk(&mut self, value: bool) -> &mut Self {
        self.inner.bulk(value);
        self
    }

    #[doc = r"Sorting options for results."]
    pub fn orderby(&mut self, value: GamesSorting) -> &mut Self {
        self.inner.orderby(value);
        self
    }

    #[doc = r"Sort direction."]
    pub fn direction(&mut self, value: Direction) -> &mut Self {
        self.inner.direction(value);
        self
    }

    /// Builds a new [`SeriesGames`]
    pub fn build(&self) -> Result<SeriesGames<'a>, SeriesGamesBuilderError> {
        let inner = self.inner.build()?;
        Ok(SeriesGames {
            id: self
                .id
                .as_ref()
                .cloned()
                .ok_or(SeriesGamesBuilderError::UninitializedField("id"))?,
            inner,
        })
    }
}

impl SeriesEmbeds {
    fn as_str(&self) -> &'static str {
        match self {
            SeriesEmbeds::Moderators => "moderators",
        }
    }
}

impl Default for SeriesSorting {
    fn default() -> Self {
        Self::NameInternational
    }
}

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

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

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

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

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

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

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

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

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

impl Pageable for ListSeries<'_> {}

impl Pageable for SeriesGames<'_> {}