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
//! The race module handles retrieving Races. A Race is a competition between multiple Runners.
//!
//! [API Documentation](https://github.com/glacials/splits-io/blob/master/docs/api.md#race)

use crate::{
    get_json, get_response,
    platform::{recv_bytes, Body},
    wrapper::{
        ContainsChatMessage, ContainsChatMessages, ContainsEntries, ContainsEntry, ContainsRace,
        ContainsRaces,
    },
    Attachment, ChatMessage, Client, DownloadSnafu, Entry, Error, Race, Visibility,
};
use http::{header::CONTENT_TYPE, Request};
use snafu::ResultExt;
use std::ops::Deref;
use url::Url;
use uuid::Uuid;

impl Race {
    /// Gets all the currently active Races on Splits.io.
    pub async fn get_active(client: &Client) -> Result<Vec<Race>, Error> {
        self::get_active(client).await
    }

    /// Gets a Race by its ID.
    pub async fn get(client: &Client, id: Uuid) -> Result<Race, Error> {
        self::get(client, id).await
    }

    /// Creates a new Race.
    pub async fn create(client: &Client, settings: Settings<'_>) -> Result<Race, Error> {
        self::create(client, settings).await
    }

    /// Updates the Race.
    pub async fn update(
        &self,
        client: &Client,
        settings: UpdateSettings<'_>,
    ) -> Result<Race, Error> {
        self::update(client, self.id, settings).await
    }

    /// Gets all of the entries for the Race.
    pub async fn entries(&self, client: &Client) -> Result<Vec<Entry>, Error> {
        self::get_entries(client, self.id).await
    }

    /// Gets the entry in the Race that is associated with the current user.
    pub async fn my_entry(&self, client: &Client) -> Result<Entry, Error> {
        self::get_entry(client, self.id).await
    }

    /// Joins the Race for the given entry.
    pub async fn join(
        &self,
        client: &Client,
        join_as: JoinAs<'_>,
        join_token: Option<&str>,
    ) -> Result<Entry, Error> {
        self::join(client, self.id, join_as, join_token).await
    }

    /// Leaves the Race for the given entry.
    pub async fn leave(&self, client: &Client, entry_id: Uuid) -> Result<(), Error> {
        self::leave(client, self.id, entry_id).await
    }

    /// Declares the given entry as ready for the Race.
    pub async fn ready_up(&self, client: &Client, entry_id: Uuid) -> Result<Entry, Error> {
        self::ready_up(client, self.id, entry_id).await
    }

    /// Undoes a ready for the given entry in th Race.
    pub async fn unready(&self, client: &Client, entry_id: Uuid) -> Result<Entry, Error> {
        self::unready(client, self.id, entry_id).await
    }

    /// Finishes the Race for the given entry.
    pub async fn finish(&self, client: &Client, entry_id: Uuid) -> Result<Entry, Error> {
        self::finish(client, self.id, entry_id).await
    }

    /// Undoes a finish for the given entry in the Race.
    pub async fn undo_finish(&self, client: &Client, entry_id: Uuid) -> Result<Entry, Error> {
        self::undo_finish(client, self.id, entry_id).await
    }

    /// Forfeits the Race for the given entry.
    pub async fn forfeit(&self, client: &Client, entry_id: Uuid) -> Result<Entry, Error> {
        self::forfeit(client, self.id, entry_id).await
    }

    /// Undoes a forfeit for the given entry in the Race.
    pub async fn undo_forfeit(&self, client: &Client, entry_id: Uuid) -> Result<Entry, Error> {
        self::undo_forfeit(client, self.id, entry_id).await
    }

    /// Gets all of the chat messages for the Race.
    pub async fn chat_messages(&self, client: &Client) -> Result<Vec<ChatMessage>, Error> {
        self::get_chat(client, self.id).await
    }

    /// Sends a message in the chat for the Race.
    pub async fn send_chat_message(
        &self,
        client: &Client,
        message: &str,
    ) -> Result<ChatMessage, Error> {
        self::send_chat_message(client, self.id, message).await
    }
}

impl Attachment {
    /// Downloads the attachment.
    pub async fn download(&self, client: &Client) -> Result<impl Deref<Target = [u8]>, Error> {
        let response = get_response(
            client,
            Request::get(&*self.url).body(Body::empty()).unwrap(),
        )
        .await?;

        recv_bytes(response.into_body())
            .await
            .context(DownloadSnafu)
    }
}

/// Gets all the currently active Races on Splits.io.
pub async fn get_active(client: &Client) -> Result<Vec<Race>, Error> {
    let ContainsRaces { races } = get_json(
        client,
        Request::get("https://splits.io/api/v4/races")
            .body(Body::empty())
            .unwrap(),
    )
    .await?;

    Ok(races)
}

// FIXME: get_all

/// Gets a Race by its ID.
pub async fn get(client: &Client, id: Uuid) -> Result<Race, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut()
        .unwrap()
        .push(id.hyphenated().encode_lower(&mut Uuid::encode_buffer()));

    let ContainsRace { race } = get_json(
        client,
        Request::get(url.as_str()).body(Body::empty()).unwrap(),
    )
    .await?;

    Ok(race)
}

/// The settings for a Race.
#[derive(Default, serde::Serialize)]
pub struct Settings<'a> {
    /// The ID of the Game that is being raced.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub game_id: Option<&'a str>,
    /// The ID of the Category that is being raced.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category_id: Option<&'a str>,
    /// Any notes that are associated with the Race.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<&'a str>,
    /// The visibility of the Race.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,
}

/// The type of update to perform on the given property.
pub enum Update<T> {
    /// Keep the previous value of the property.
    Keep,
    /// Clear the value of the property.
    Clear,
    /// Change the value of the property.
    Set(T),
}

impl<T> Update<T> {
    fn is_keep(&self) -> bool {
        matches!(self, Update::Keep)
    }
}

impl<T> Default for Update<T> {
    fn default() -> Self {
        Update::Keep
    }
}

impl<T: serde::Serialize> serde::Serialize for Update<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Update::Set(val) => serializer.serialize_some(val),
            _ => serializer.serialize_none(),
        }
    }
}

/// The new properties to use for a Race when performing an update.
#[derive(Default, serde::Serialize)]
pub struct UpdateSettings<'a> {
    /// The update to perform for the ID of the Game that is being raced.
    #[serde(skip_serializing_if = "Update::is_keep")]
    pub game_id: Update<&'a str>,
    /// The update to perform for the ID of the Category that is being raced.
    #[serde(skip_serializing_if = "Update::is_keep")]
    pub category_id: Update<&'a str>,
    /// The update to perform for any notes that are associated with the Race.
    #[serde(skip_serializing_if = "Update::is_keep")]
    pub notes: Update<&'a str>,
    /// The update to perform for the visibility of the Race.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,
}

/// Creates a new Race.
pub async fn create(client: &Client, settings: Settings<'_>) -> Result<Race, Error> {
    let ContainsRace { race } = get_json(
        client,
        Request::post("https://splits.io/api/v4/races")
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(serde_json::to_vec(&settings).unwrap()))
            .unwrap(),
    )
    .await?;

    Ok(race)
}

/// Updates a Race.
pub async fn update(
    client: &Client,
    id: Uuid,
    settings: UpdateSettings<'_>,
) -> Result<Race, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut()
        .unwrap()
        .push(id.hyphenated().encode_lower(&mut Uuid::encode_buffer()));

    let ContainsRace { race } = get_json(
        client,
        Request::patch(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(serde_json::to_vec(&settings).unwrap()))
            .unwrap(),
    )
    .await?;

    Ok(race)
}

/// Gets all of the entries for a Race.
pub async fn get_entries(client: &Client, id: Uuid) -> Result<Vec<Entry>, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        id.hyphenated().encode_lower(&mut Uuid::encode_buffer()),
        "entries",
    ]);

    let ContainsEntries { entries } = get_json(
        client,
        Request::get(url.as_str()).body(Body::empty()).unwrap(),
    )
    .await?;

    Ok(entries)
}

/// Gets the entry in a Race that is associated with the current user.
pub async fn get_entry(client: &Client, id: Uuid) -> Result<Entry, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        id.hyphenated().encode_lower(&mut Uuid::encode_buffer()),
        "entry",
    ]);

    let ContainsEntry { entry } = get_json(
        client,
        Request::get(url.as_str()).body(Body::empty()).unwrap(),
    )
    .await?;

    Ok(entry)
}

/// The type of racer to join the Race as.
pub enum JoinAs<'a> {
    /// Join the Race as a regular user.
    Myself,
    /// Join the Race as a ghost of a past Run.
    Ghost(&'a str),
}

#[derive(serde::Serialize)]
struct JoinToken<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    join_token: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    entry: Option<JoinEntry<'a>>,
}

#[derive(serde::Serialize)]
struct JoinEntry<'a> {
    run_id: &'a str,
}

/// Joins the Race for the given entry.
pub async fn join(
    client: &Client,
    race_id: Uuid,
    join_as: JoinAs<'_>,
    join_token: Option<&str>,
) -> Result<Entry, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        race_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
        "entries",
    ]);

    let ContainsEntry { entry } = get_json(
        client,
        Request::post(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_vec(&JoinToken {
                    join_token,
                    entry: match join_as {
                        JoinAs::Myself => None,
                        JoinAs::Ghost(run_id) => Some(JoinEntry { run_id }),
                    },
                })
                .unwrap(),
            ))
            .unwrap(),
    )
    .await?;

    Ok(entry)
}

/// Leaves the Race for the given entry.
pub async fn leave(client: &Client, race_id: Uuid, entry_id: Uuid) -> Result<(), Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        race_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
        "entries",
        entry_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
    ]);

    get_response(
        client,
        Request::delete(url.as_str()).body(Body::empty()).unwrap(),
    )
    .await?;

    Ok(())
}

#[derive(serde::Serialize)]
struct UpdateEntry<T> {
    entry: T,
}

#[derive(serde::Serialize)]
struct ReadyState {
    readied_at: Option<&'static str>,
}

#[derive(serde::Serialize)]
struct FinishState {
    finished_at: Option<&'static str>,
}

#[derive(serde::Serialize)]
struct ForfeitState {
    forfeited_at: Option<&'static str>,
}

/// Declares the given entry as ready for a Race.
pub async fn ready_up(client: &Client, race_id: Uuid, entry_id: Uuid) -> Result<Entry, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        race_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
        "entries",
        entry_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
    ]);

    let ContainsEntry { entry } = get_json(
        client,
        Request::patch(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_vec(&UpdateEntry {
                    entry: ReadyState {
                        readied_at: Some("now"),
                    },
                })
                .unwrap(),
            ))
            .unwrap(),
    )
    .await?;

    Ok(entry)
}

/// Undoes a ready for the given entry in a Race.
pub async fn unready(client: &Client, race_id: Uuid, entry_id: Uuid) -> Result<Entry, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        race_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
        "entries",
        entry_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
    ]);

    let ContainsEntry { entry } = get_json(
        client,
        Request::patch(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_vec(&UpdateEntry {
                    entry: ReadyState { readied_at: None },
                })
                .unwrap(),
            ))
            .unwrap(),
    )
    .await?;

    Ok(entry)
}

/// Finishes the Race for the given entry.
pub async fn finish(client: &Client, race_id: Uuid, entry_id: Uuid) -> Result<Entry, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        race_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
        "entries",
        entry_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
    ]);

    let ContainsEntry { entry } = get_json(
        client,
        Request::patch(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_vec(&UpdateEntry {
                    entry: FinishState {
                        finished_at: Some("now"),
                    },
                })
                .unwrap(),
            ))
            .unwrap(),
    )
    .await?;

    Ok(entry)
}

/// Undoes a finish for the given entry in a Race.
pub async fn undo_finish(client: &Client, race_id: Uuid, entry_id: Uuid) -> Result<Entry, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        race_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
        "entries",
        entry_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
    ]);

    let ContainsEntry { entry } = get_json(
        client,
        Request::patch(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_vec(&UpdateEntry {
                    entry: FinishState { finished_at: None },
                })
                .unwrap(),
            ))
            .unwrap(),
    )
    .await?;

    Ok(entry)
}

/// Forfeits the Race for the given entry.
pub async fn forfeit(client: &Client, race_id: Uuid, entry_id: Uuid) -> Result<Entry, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        race_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
        "entries",
        entry_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
    ]);

    let ContainsEntry { entry } = get_json(
        client,
        Request::patch(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_vec(&UpdateEntry {
                    entry: ForfeitState {
                        forfeited_at: Some("now"),
                    },
                })
                .unwrap(),
            ))
            .unwrap(),
    )
    .await?;

    Ok(entry)
}

/// Undoes a forfeit for the given entry in a Race.
pub async fn undo_forfeit(client: &Client, race_id: Uuid, entry_id: Uuid) -> Result<Entry, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        race_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
        "entries",
        entry_id
            .hyphenated()
            .encode_lower(&mut Uuid::encode_buffer()),
    ]);

    let ContainsEntry { entry } = get_json(
        client,
        Request::patch(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_vec(&UpdateEntry {
                    entry: ForfeitState { forfeited_at: None },
                })
                .unwrap(),
            ))
            .unwrap(),
    )
    .await?;

    Ok(entry)
}

/// Gets all of the chat messages for a Race.
pub async fn get_chat(client: &Client, id: Uuid) -> Result<Vec<ChatMessage>, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        id.hyphenated().encode_lower(&mut Uuid::encode_buffer()),
        "chat",
    ]);

    let ContainsChatMessages { chat_messages } = get_json(
        client,
        Request::get(url.as_str()).body(Body::empty()).unwrap(),
    )
    .await?;

    Ok(chat_messages)
}

#[derive(serde::Serialize)]
struct SendMessage<'a> {
    chat_message: SendMessageBody<'a>,
}

#[derive(serde::Serialize)]
struct SendMessageBody<'a> {
    body: &'a str,
}

/// Sends a message in the chat for a Race.
pub async fn send_chat_message(
    client: &Client,
    id: Uuid,
    message: &str,
) -> Result<ChatMessage, Error> {
    let mut url = Url::parse("https://splits.io/api/v4/races").unwrap();
    url.path_segments_mut().unwrap().extend(&[
        id.hyphenated().encode_lower(&mut Uuid::encode_buffer()),
        "chat",
    ]);

    let ContainsChatMessage { chat_message } = get_json(
        client,
        Request::post(url.as_str())
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(
                serde_json::to_vec(&SendMessage {
                    chat_message: SendMessageBody { body: message },
                })
                .unwrap(),
            ))
            .unwrap(),
    )
    .await?;

    Ok(chat_message)
}