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

//! API Wrapper for the [TASVideos API](https://demo.tasvideos.org/api/).
//! 
//! This crate provides synchronous functions for each supported endpoint of the API.
//! 
//! All requests can be used without an API key, however, the [`USER_AGENT`] string should be set
//! before making any requests. 

use lazy_static::lazy_static;
use reqwest::blocking::{Client, RequestBuilder};
use reqwest::header::HeaderValue;
use serde::{Deserialize, Serialize};
use Filter::*;
use crate::Error::Reqwest;

/// The `User-Agent` header used in all requests made from this crate.
/// 
/// The user agent string should be set before making any API requests. This string should include
/// some contact method (e.g. email), and either your name or the name of your software.
/// 
/// This can be set using [`set_user_agent()`] or the following:
/// ```rust
/// unsafe { tasvideos_api_rs::USER_AGENT = "John Smith (johnsmith@gmail.com)"; }
/// ```
/// 
/// [`set_user_agent()`]: set_user_agent
pub static mut USER_AGENT: &'static str = "";

/// The base URL used in all requests to the TASVideos API. Default is `https://tasvideos.org/api/v1/`.
/// 
/// If you wish to change this, use the following:
/// ```rust
/// unsafe { tasvideos_api_rs::API_URL = "https://custom.url/here/"; }
/// ```
pub static mut API_URL: &'static str = "https://tasvideos.org/api/v1/";

lazy_static! {
    static ref CLIENT: Client = {
        //std::fs::write("staging-tasvideos-org-chain.pem", include_bytes!("../staging-tasvideos-org-chain.pem")).unwrap();
        //std::env::set_var("SSL_CERT_FILE", "staging-tasvideos-org-chain.pem");
        
        Client::builder()
            .use_native_tls()
            .build().unwrap()
        };
}

/// Helper fuction that sets the static [`USER_AGENT`] string used in API requests.
/// 
/// ```rust
/// tasvideos_api_rs::set_user_agent("John Smith (johnsmith@gmail.com)");
/// ```
pub fn set_user_agent(agent: &'static str) {
    unsafe { USER_AGENT = agent; }
}

pub const MAX_PAGE_LENGTH: u32 = 1000;

#[derive(Debug)]
pub enum Error {
    Reqwest(reqwest::Error),
}
pub type Result<T> = std::result::Result<T, Error>;


/// Some endpoints can use these filters to refine what data is returned.
/// 
/// Endpoints that support filters will accept a `Vec<QueryFilter>` argument. The order of filters
/// doesn't matter. Using multiple of the same kind of filter is not recommended, and may produce
/// undefined behavior. Each endpoint may not support all available filter types, refer to the docs
/// on each function to know what is supported. Any unsupported filters will be quietly ignored.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum Filter {
    Statuses(Vec<String>),
    Users(Vec<String>),
    Systems(Vec<String>),
    ClassNames(Vec<String>),
    StartYear(i32),
    EndYear(i32),
    GenreNames(Vec<String>),
    TagNames(Vec<String>),
    FlagNames(Vec<String>),
    AuthorIds(Vec<i32>),
    ShowObsoleted(bool),
    GameIds(Vec<i32>),
    Games(Vec<i32>),
    GameGroupIds(Vec<i32>),
    PageSize(u32),
    CurrentPage(u32),
    Sorts(Vec<String>),
}
impl Filter {
    pub fn query_push(&self, query_seq: &mut Vec<(String, String)>) {
        match self {
            Statuses(x) => query_seq.push(("Statuses".to_owned(), comma_separate(x))),
            Users(x) => query_seq.push(("User".to_owned(), comma_separate(x))),
            Systems(x) => query_seq.push(("Systems".to_owned(), comma_separate(x))),
            ClassNames(x) => query_seq.push(("ClassNames".to_owned(), comma_separate(x))),
            StartYear(x) => query_seq.push(("StartYear".to_owned(), x.to_string())),
            EndYear(x) => query_seq.push(("EndYear".to_owned(), x.to_string())),
            GenreNames(x) => query_seq.push(("GenreNames".to_owned(), comma_separate(x))),
            TagNames(x) => query_seq.push(("TagNames".to_owned(), comma_separate(x))),
            FlagNames(x) => query_seq.push(("FlagNames".to_owned(), comma_separate(x))),
            AuthorIds(x) => query_seq.push(("AuthorIds".to_owned(), comma_separate(&x.iter().map(|id| id.to_string()).collect()))),
            ShowObsoleted(x) => query_seq.push(("ShowObsoleted".to_owned(), x.to_string())),
            GameIds(x) => query_seq.push(("GameIds".to_owned(), comma_separate(&x.iter().map(|id| id.to_string()).collect()))),
            Games(x) => query_seq.push(("Games".to_owned(), comma_separate(&x.iter().map(|id| id.to_string()).collect()))),
            GameGroupIds(x) => query_seq.push(("GameGroupIds".to_owned(), comma_separate(&x.iter().map(|id| id.to_string()).collect()))),
            PageSize(x) => query_seq.push(("PageSize".to_owned(), x.to_string())),
            CurrentPage(x) => query_seq.push(("CurrentPage".to_owned(), x.to_string())),
            Sorts(x) => query_seq.push(("Sort".to_owned(), comma_separate(x))),
        }
    }
}

/// Represents a TASVideos game version (e.g. ROM).
#[derive(Clone, Deserialize, Serialize, Eq, PartialEq, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct GameVersion {
    pub id: Option<i32>,
    pub md5: Option<String>,
    pub sha1: Option<String>,
    pub name: Option<String>,
    #[serde(rename = "type")]
    pub kind: Option<i32>,
    pub region: Option<String>,
    pub version: Option<String>,
    pub system_code: Option<String>,
}

/// Represents a TASVideos game.
#[derive(Clone, Deserialize, Serialize, Eq, PartialEq, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct Game {
    pub id: Option<i32>,
    pub versions: Option<Vec<GameVersion>>,
    pub display_name: Option<String>,
    pub abbreviation: Option<String>,
    pub aliases: Option<String>,
    pub screenshot_url: Option<String>,
}

/// Represents a TASVideos movie publication.
#[derive(Clone, Deserialize, Serialize, PartialEq, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct Publication {
    pub id: Option<i32>,
    pub title: Option<String>,
    pub branch: Option<String>,
    pub emulator_version: Option<String>,
    pub class: Option<String>,
    pub system_code: Option<String>,
    pub submission_id: Option<i32>,
    pub game_id: Option<i32>,
    pub game_version_id: Option<i32>,
    pub obsoleted_by_id: Option<i32>,
    pub frames: Option<i32>,
    pub rerecord_count: Option<i32>,
    pub system_frame_rate: Option<f64>,
    pub movie_file_name: Option<String>,
    pub additional_authors: Option<String>,
    pub authors: Option<Vec<String>>,
    pub tags: Option<Vec<String>>,
    pub flags: Option<Vec<String>>,
    pub urls: Option<Vec<String>>,
    pub file_paths: Option<Vec<String>>,
}

/// Represents a TASVideos movie submission.
#[derive(Clone, Deserialize, Serialize, PartialEq, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct Submission {
    pub id: Option<i32>,
    pub publication_id: Option<i32>,
    pub title: Option<String>,
    pub intended_class: Option<String>,
    pub judge: Option<String>,
    pub publisher: Option<String>,
    pub status: Option<String>,
    pub movie_extension: Option<String>,
    pub game_id: Option<i32>,
    pub game_name: Option<String>,
    pub game_version_id: Option<i32>,
    pub game_version: Option<String>,
    pub system_code: Option<String>,
    pub system_frame_rate: Option<f64>,
    pub frames: Option<i32>,
    pub rerecord_count: Option<i32>,
    pub encode_embed_link: Option<String>,
    pub branch: Option<String>,
    pub rom_name: Option<String>,
    pub emulator_version: Option<String>,
    pub movie_start_type: Option<i32>,
    pub additional_authors: Option<String>,
    pub authors: Option<Vec<String>>,
}

/// Describes a possible framerate for a gaming system.
#[derive(Clone, Deserialize, Serialize, PartialEq, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct SystemFrameRate {
    pub id: Option<i32>,
    pub frame_rate: Option<f64>,
    pub region_code: Option<String>,
    pub preliminary: Option<bool>,
    pub obsolete: Option<bool>,
}

/// Represents a gaming system (e.g. GBA, N64, Genesis, etc.) used by TASVideos.
#[derive(Clone, Deserialize, Serialize, PartialEq, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct System {
    pub id: Option<i32>,
    pub code: Option<String>,
    pub display_name: Option<String>,
    pub system_frame_rates: Option<Vec<SystemFrameRate>>,
}


/// Creates a GET request builder for the TASVideos API.
/// 
/// The URL is set by appending the predefined [`API_URL`] with the provided endpoint.
/// A `User-Agent` header (using the static [`USER_AGENT`]) and the appropriate `Accept` header are also set.
/// 
/// This can be used to create custom requests to the API, such as using an endpoint that's unimplemented in this crate.
pub fn get(endpoint: &str) -> RequestBuilder {
    unsafe {
        let mut builder = CLIENT.get([API_URL, endpoint].concat()).header("Accept", "application/json");
        
        if !USER_AGENT.is_empty() {
            builder = builder.header("User-Agent", USER_AGENT);
        }
        
        builder
    }
}


/// Executes a GET request to the `/Games/{id}` endpoint to retrieve a specific [`game`].
/// 
/// # Errors
/// 
/// If any request error occurs, or if no game with this `id` is found (resulting in a parsing error),
/// the error will be returned.
/// 
/// [`game`]: Game
pub fn get_game(id: i32) -> Result<Game> {
    match get(&["Games/", &id.to_string()].concat()).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(res) => match res.json() {
                Ok(data) => Ok(data),
                Err(err) => Err(Reqwest(err)),
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Executes a GET request to the `/Games` endpoint to retrieve a list of [`games`].
/// 
/// Unless configured with a filter, only the first 100 (or fewer) games will be returned.
/// 
/// Optional search filters:
/// 
/// [`Systems`], [`PageSize`], [`CurrentPage`], [`Sorts`]
/// 
/// # Errors
/// 
/// Any request or parsing errors will be returned. 
/// 
/// [`games`]: Game
pub fn get_games<F: AsRef<[Filter]>>(filters: F) -> Result<Vec<Game>> {
    let mut query = Vec::new();
    for filter in filters.as_ref() { match filter {
        Systems(_) | PageSize(_) | CurrentPage(_) | Sorts(_) => filter.query_push(&mut query),
        _ => ()
    }}
    
    match get("Games").query(&query).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(res) => match res.json() {
                Ok(data) => Ok(data),
                Err(err) => Err(Reqwest(err)),
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Executes one or more GET requests to the `/Games` endpoint to retreive all available [`games`].
/// 
/// This will likely make multiple API calls, in [`MAX_PAGE_LENGTH`] increments, until no more entries are
/// found or until an error occurs.
/// 
/// Optional search filters:
/// 
/// [`System`], [`Sorts`]
/// 
/// # Errors
/// 
/// Any request or parsing errors will be returned. 
/// 
/// [`games`]: Game
pub fn get_games_all<F: AsRef<[Filter]>>(filters: F) -> Result<Vec<Game>> {
    let mut games = Vec::new();
    let mut filters = filters.as_ref().to_vec();
    for (i, filter) in filters.iter().enumerate() { match filter { 
        PageSize(_) | CurrentPage(_) => { filters.remove(i); break; },
        _ => ()
    }}
    filters.push(PageSize(MAX_PAGE_LENGTH));
    filters.push(CurrentPage(1));
    
    loop {
        let result = get_games(&filters);
        
        for filter in filters.iter_mut() { match filter {
            CurrentPage(x) => *x += 1,
            _ => ()
        }}
        
        match result {
            Ok(mut data) => {
                let len = data.len();
                games.append(&mut data);
                if len < MAX_PAGE_LENGTH as usize { break }
            },
            Err(err) => return Err(err),
        }
    }
    
    Ok(games)
}



/// Executes a GET request to the `/Publications/{id}` endpoint to retrieve a specific [`publication`].
/// 
/// # Errors
/// 
/// If any request error occurs, or if no publication with this `id` is found (resulting in a parsing error),
/// the error will be returned.
/// 
/// [`publication`]: Publication
pub fn get_publication(id: i32) -> Result<Publication> {
    match get(&["Publications/", &id.to_string()].concat()).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(res) => match res.json() {
                Ok(data) => Ok(data),
                Err(err) => Err(Reqwest(err)),
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Executes a GET request to the `/Publications` endpoint to retrieve a list of [`publications`].
/// 
/// Unless configured with a filter, only the first 100 (or fewer) publications will be returned.
/// 
/// Optional search filters:
/// 
/// [`Systems`], [`ClassNames`], [`StartYear`], [`EndYear`], [`GenreNames`], [`TagNames`],
/// [`FlagNames`], [`AuthorIds`], [`ShowObsoleted`], [`GameIds`], [`GameGroupIds`],
/// [`PageSize`], [`CurrentPage`], [`Sorts`]
/// 
/// # Errors
/// 
/// Any request or parsing errors will be returned. 
/// 
/// [`publications`]: Publication
pub fn get_publications<F: AsRef<[Filter]>>(filters: F) -> Result<Vec<Publication>> {
    let mut query = Vec::new();
    for filter in filters.as_ref() { match filter {
        Systems(_) | ClassNames(_) | StartYear(_) | EndYear(_) | GenreNames(_) |
            TagNames(_) | FlagNames(_) | AuthorIds(_) | ShowObsoleted(_) | GameIds(_) |
            GameGroupIds(_) | PageSize(_) | CurrentPage(_) | Sorts(_) => filter.query_push(&mut query),
        _ => ()
    }}
    
    match get("Publications").query(&query).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(res) => match res.json() {
                Ok(data) => Ok(data),
                Err(err) => Err(Reqwest(err)),
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Executes one or more GET requests to the `/Publications` endpoint to retreive all available [`publications`].
/// 
/// This will likely make multiple API calls, in [`MAX_PAGE_LENGTH`] increments, until no more entries are
/// found or until an error occurs.
/// 
/// Optional search filters:
/// 
/// [`Systems`], [`ClassNames`], [`StartYear`], [`EndYear`], [`GenreNames`], [`TagNames`],
/// [`FlagNames`], [`AuthorIds`], [`ShowObsoleted`], [`GameIds`], [`GameGroupIds`], [`Sorts`]
/// 
/// # Errors
/// 
/// Any request or parsing errors will be returned. 
/// 
/// [`publications`]: Publication
pub fn get_publications_all<F: AsRef<[Filter]>>(filters: F) -> Result<Vec<Publication>> {
    let mut publications = Vec::new();
    let mut filters = filters.as_ref().to_vec();
    for (i, filter) in filters.iter().enumerate() { match filter { 
        PageSize(_) | CurrentPage(_) => { filters.remove(i); break; },
        _ => ()
    }}
    filters.push(PageSize(MAX_PAGE_LENGTH));
    filters.push(CurrentPage(1));
    
    loop {
        let result = get_publications(&filters);
        
        for filter in filters.iter_mut() { match filter {
            CurrentPage(x) => *x += 1,
            _ => ()
        }}
        
        match result {
            Ok(mut data) => {
                let len = data.len();
                publications.append(&mut data);
                if len < MAX_PAGE_LENGTH as usize { break }
            },
            Err(err) => return Err(err),
        }
    }
    
    Ok(publications)
}

/// Attempts to download the publication's movie file.
/// 
/// Returned data _should_ be a ZIP archive.
pub fn get_publication_movie(id: i32) -> Result<Vec<u8>> {
    match CLIENT.get(format!("https://tasvideos.org/{}M?handler=Download", id)).header("User-Agent", unsafe { USER_AGENT }).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(data) => Ok(data.bytes().unwrap_or_default().to_vec()),
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}


/// Executes a GET request to the `/Submissions/{id}` endpoint to retrieve a specific [`submission`].
/// 
/// # Errors
/// 
/// If any request error occurs, or if no submission with this `id` is found (resulting in a parsing error),
/// the error will be returned.
/// 
/// [`submission`]: Submission
pub fn get_submission(id: i32) -> Result<Submission> {
    match get(&["Submissions/", &id.to_string()].concat()).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(res) => match res.json() {
                Ok(data) => Ok(data),
                Err(err) => Err(Reqwest(err)),
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Executes a GET request to the `/Submissions` endpoint to retrieve a list of [`submissions`].
/// 
/// Unless configured with a filter, only the first 100 (or fewer) submissions will be returned.
/// 
/// Optional search filters:
/// 
/// [`Statuses`], [`Users`], [`StartYear`], [`EndYear`], [`Systems`], [`Games`],
/// [`PageSize`], [`CurrentPage`], [`Sorts`]
/// 
/// # Errors
/// 
/// Any request or parsing errors will be returned. 
/// 
/// [`submissions`]: Submission
pub fn get_submissions<F: AsRef<[Filter]>>(filters: F) -> Result<Vec<Submission>> {
    let mut query = Vec::new();
    for filter in filters.as_ref() { match filter {
        Statuses(_) | Users(_) | StartYear(_) | EndYear(_) | Systems(_) |
            Games(_) | PageSize(_) | CurrentPage(_) | Sorts(_) => filter.query_push(&mut query),
        _ => ()
    }}
    
    match get("Submissions").query(&query).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(res) => match res.json() {
                Ok(data) => Ok(data),
                Err(err) => Err(Reqwest(err)),
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Executes one or more GET requests to the `/Submissions` endpoint to retreive all available [`submissions`].
/// 
/// This will likely make multiple API calls, in [`MAX_PAGE_LENGTH`] increments, until no more entries are
/// found or until an error occurs.
/// 
/// Optional search filters:
/// 
/// [`Statuses`], [`Users`], [`StartYear`], [`EndYear`], [`Systems`], [`Games`], [`Sorts`]
/// 
/// # Errors
/// 
/// Any request or parsing errors will be returned. 
/// 
/// [`submissions`]: Submission
pub fn get_submissions_all<F: AsRef<[Filter]>>(filters: F) -> Result<Vec<Submission>> {
    let mut submissions = Vec::new();
    let mut filters = filters.as_ref().to_vec();
    for (i, filter) in filters.iter().enumerate() { match filter { 
        PageSize(_) | CurrentPage(_) => { filters.remove(i); break; },
        _ => ()
    }}
    filters.push(PageSize(MAX_PAGE_LENGTH));
    filters.push(CurrentPage(1));
    
    loop {
        let result = get_submissions(&filters);
        
        for filter in filters.iter_mut() { match filter {
            CurrentPage(x) => *x += 1,
            _ => ()
        }}
        
        match result {
            Ok(mut data) => {
                let len = data.len();
                submissions.append(&mut data);
                if len < MAX_PAGE_LENGTH as usize { break }
            },
            Err(err) => return Err(err),
        }
    }
    
    Ok(submissions)
}

/// Attempts to download the submission's movie file.
/// 
/// Returned data _should_ be a ZIP archive.
pub fn get_submission_movie(id: i32) -> Result<Vec<u8>> {
    match CLIENT.get(format!("https://tasvideos.org/{}S?handler=Download", id)).header("User-Agent", unsafe { USER_AGENT }).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(data) => Ok(data.bytes().unwrap_or_default().to_vec()),
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Attempts to download a userfile.
/// 
/// Returned data _should_ be gzip compressed.
pub fn get_userfile(id: u64) -> Result<(Vec<u8>, Option<String>)> {
    match CLIENT.get(format!("https://tasvideos.org/UserFiles/Info/{}?handler=Download", id)).header("User-Agent", unsafe { USER_AGENT }).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(data) => {
                let default_header = HeaderValue::from_static("");
                let header = data.headers().get("content-disposition").unwrap_or(&default_header).to_str().unwrap_or("");
                if !header.is_empty() {
                    let parts: Vec<&str> = header.split(';').filter(|part| part.contains("filename=")).collect();
                    if let Some(part) = parts.first() {
                        let part = part.trim();
                        if part.len() > 9 {
                            let filename = part[9..].trim_matches('"').to_string();
                            if !filename.is_empty() {
                                return Ok((data.bytes().unwrap_or_default().to_vec(), Some(filename)));
                            }
                        }
                    }
                }
                
                Ok((data.bytes().unwrap_or_default().to_vec(), None))
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Executes a GET request to the `/Systems/{id}` endpoint to retrieve a specific [`system`].
/// 
/// # Errors
/// 
/// If any request error occurs, or if no system with this `id` is found (resulting in a parsing error),
/// the error will be returned.
/// 
/// [`system`]: System
pub fn get_system(id: i32) -> Result<System> {
    match get(&["Systems/", &id.to_string()].concat()).build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(res) => match res.json() {
                Ok(data) => Ok(data),
                Err(err) => Err(Reqwest(err)),
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}

/// Executes a GET request to the `/Systems` endpoint to retrieve a list of all [`systems`].
/// 
/// Unlike similar endpoints, this endpoint doesn't accept any filters, and should always return
/// all available systems, using a single request.
/// 
/// # Errors
/// 
/// Any request or parsing errors will be returned. 
/// 
/// [`systems`]: System
pub fn get_systems() -> Result<Vec<System>> {
    match get("Systems").build() {
        Ok(req) => match CLIENT.execute(req) {
            Ok(res) => match res.json() {
                Ok(data) => Ok(data),
                Err(err) => Err(Reqwest(err)),
            },
            Err(err) => Err(Reqwest(err)),
        },
        Err(err) => Err(Reqwest(err)),
    }
}





fn comma_separate<T: AsRef<str>>(vec: &Vec<T>) -> String {
    let mut out = String::new();
    
    for s in vec {
        out.push_str(s.as_ref());
        out.push_str(",");
    }
    
    out.trim_end_matches(',').to_string()
}