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
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
//! Client library for the [Toornament](https://www.toornament.com) web API.
//!
//! Log in to Toornament with `Toornament::with_application`.
//! Call API methods to interact with the service directly or user an iterator-like interface to
//! work with it in more rust-idiomatic way.
//!
//! For Toornament API documentation [look here]
//! (https://developer.toornament.com/overview/get-started).
//!
//! For examples, see the `examples` directory in the source tree.
//!
//! For more readings, look at the [`toornament-rs book`](https://vityafx.github.io/toornament-rs).
//!
//! # Usage
//!
//! Start by creating and instance `Toornament` structure and then perform the requests:
//!
//! ```rust,no_run
//! use toornament::*;
//!
//! let toornament = Toornament::with_application("API_TOKEN",
//!                                               "CLIENT_ID",
//!                                               "CLIENT_SECRET").unwrap();
//! println!("Disciplines: {:?}", toornament.disciplines(None));
//! println!("Disciplines: {:?}", toornament.disciplines_iter()
//!                                         .all()
//!                                         .collect::<Disciplines>());
//! ```
//!
//! # Additional notes
//! The `Toornament` structure is `Send` and `Sync`, so it can be simply shared among
//! threads. Also, the `Toornament` objects may live as long as you need to: the object will
//! refresh it's access token once it is expired, so you may just create it once and use
//! everywhere.
#![warn(missing_docs)]
extern crate chrono;
#[macro_use]
extern crate log;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

use std::io::Read;
use std::sync::Mutex;

#[macro_use]
mod macroses;
mod common;
mod disciplines;
mod endpoints;
mod error;
mod filters;
mod games;
pub mod info;
pub mod iter;
mod matches;
mod opponents;
mod participants;
mod permissions;
mod stages;
mod streams;
mod tournaments;
mod videos;

pub use common::{Date, MatchResultSimple, TeamSize};
pub use disciplines::{AdditionalFields, Discipline, DisciplineId, Disciplines};
use endpoints::Endpoint;
pub use error::{
    Error, IterError, Result, ToornamentError, ToornamentErrorScope, ToornamentErrorType,
    ToornamentErrors, ToornamentServiceError,
};
pub use filters::{
    CreateDateSortFilter, DateSortFilter, MatchFilter, TournamentParticipantsFilter,
    TournamentVideosFilter,
};
pub use games::{Game, GameNumber, Games};
pub use iter::*;
pub use matches::{Match, MatchFormat, MatchId, MatchResult, MatchStatus, MatchType, Matches};
pub use opponents::{Opponent, Opponents};
pub use participants::{
    CustomField, CustomFieldType, CustomFields, Participant, ParticipantId, ParticipantLogo,
    ParticipantType, Participants,
};
pub use permissions::{
    Permission, PermissionAttribute, PermissionAttributes, PermissionId, Permissions,
};
pub use stages::{Stage, StageNumber, StageType, Stages};
pub use streams::{Stream, StreamId, Streams};
pub use tournaments::{Tournament, TournamentId, TournamentStatus, Tournaments};
pub use videos::{Video, VideoCategory, Videos};

/// Create the request builer.
macro_rules! build_request {
    ($toornament:ident, $method:ident, $address:expr) => {{
        $toornament
            .client
            .$method($address)
            .header("X-Api-Key", $toornament.keys.0.clone())
            .bearer_auth(&$toornament.fresh_token()?)
    }};
}

/// Macro only for internal use with the `Toornament` object (relies on it's fields)
macro_rules! request {
    ($toornament:ident, $method:ident, $address:expr) => {{
        build_request!($toornament, $method, $address).send()
    }};
}

/// Macro only for internal use with the `Toornament` object (relies on it's fields)
macro_rules! request_body {
    ($toornament:ident, $method:ident, $address:expr, $body:expr) => {{
        build_request!($toornament, $method, $address)
            .body($body)
            .send()
    }};
}

#[derive(Debug, Clone)]
struct AccessToken {
    access_token: String,
    expires: u64,
}

fn parse_token<R: Read>(json_str: R) -> Result<AccessToken> {
    #[derive(Debug, Clone, Deserialize)]
    struct OauthAccessToken {
        access_token: String,
        expires_in: u64,
        token_type: String,
        scope: Option<String>,
    }

    let oauth = serde_json::from_reader::<_, OauthAccessToken>(json_str)?;
    Ok(AccessToken {
        access_token: oauth.access_token,
        expires: chrono::Local::now().timestamp() as u64 + oauth.expires_in,
    })
}

fn authenticate(
    client: &reqwest::blocking::Client,
    client_id: &str,
    client_secret: &str,
) -> Result<AccessToken> {
    use std::collections::HashMap;

    let mut params = HashMap::new();
    params.insert("grant_type", "client_credentials");
    params.insert("client_id", client_id);
    params.insert("client_secret", client_secret);
    parse_token(
        client
            .post(&Endpoint::OauthToken.to_string())
            .form(&params)
            .send()?,
    )
}

/// Main structure. Should be your point of start using the service.
/// This struct covers all the `toornament` API.
#[derive(Debug)]
pub struct Toornament {
    client: reqwest::blocking::Client,
    keys: (String, String, String),
    oauth_token: Mutex<AccessToken>,
}
impl Toornament {
    /// Returns currently stored token
    fn current_token(&self) -> Result<String> {
        match self.oauth_token.lock() {
            Ok(g) => Ok(g.access_token.to_owned()),
            Err(_) => Err(Error::Rest("Can't get the token")),
        }
    }

    /// Always returns fresh token (refreshes it if neeeded)
    fn fresh_token(&self) -> Result<String> {
        let mut need_refresh = false;
        {
            let access_token = match self.oauth_token.lock() {
                Ok(g) => g,
                Err(_) => return Err(Error::Rest("Can't get the token")),
            };
            if chrono::Local::now().timestamp() as u64 > access_token.expires {
                need_refresh = true;
            }
        }
        if need_refresh && !self.refresh() {
            return Err(Error::Rest("Could not refresh the token"));
        }

        self.current_token()
    }

    /// Creates new `Toornament` object with client credentials
    /// which is your user API_Token, application's client id and secret.
    /// You may obtain application's credentials [here]
    /// (https://developer.toornament.com/applications/) (You must be logged in to open the page).
    /// This method connects to the toornament service and if there is a error it returns the `Error`
    /// object and on success it returns `Toornament` object.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET");
    /// assert!(t.is_ok());
    /// ```
    pub fn with_application<S: Into<String>>(
        api_token: S,
        client_id: S,
        client_secret: S,
    ) -> Result<Toornament> {
        let client = reqwest::blocking::Client::new();
        let keys = (api_token.into(), client_id.into(), client_secret.into());
        let token = authenticate(&client, &keys.1, &keys.2)?;

        Ok(Toornament {
            client,
            keys,
            oauth_token: Mutex::new(token),
        })
    }

    /// Refreshes the oauth token. Automatically used when it is expired.
    pub fn refresh(&self) -> bool {
        let mut g = match self.oauth_token.lock() {
            Ok(g) => g,
            Err(e) => {
                error!("Unable to refresh token: {:?}", e);
                return false;
            }
        };

        match authenticate(&self.client, &self.keys.1, &self.keys.2) {
            Ok(token) => {
                *g = token;
                true
            }
            Err(e) => {
                error!("Unable to refresh token: {:?}", e);
                false
            }
        }
    }

    /// Consumes `Toornament` object and sets timeout to it
    pub fn timeout(mut self, seconds: u64) -> Result<Toornament> {
        use std::time::Duration;

        self.client = reqwest::blocking::ClientBuilder::new()
            .timeout(Duration::from_secs(seconds))
            .build()?;
        Ok(self)
    }

    /// Returns Iterator-like objects to work with tournaments and it's subobjects.
    pub fn tournaments_iter(&self) -> iter::TournamentsIter {
        iter::TournamentsIter::new(self)
    }

    /// Returns Iterator-like objects to work with disciplines and it's subobjects.
    pub fn disciplines_iter(&self) -> iter::DisciplinesIter {
        iter::DisciplinesIter::new(self)
    }

    /// [Returns either a collection of disciplines]
    /// (https://developer.toornament.com/doc/disciplines#get:disciplines) if id is None or
    /// [a disciplines with the detail of his features]
    /// (https://developer.toornament.com/doc/disciplines#get:disciplines:id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Getting all disciplines
    /// let all_disciplines: Disciplines = t.disciplines(None).unwrap();
    /// // Get discipline by it's id
    /// let wwe2k17_discipline = t.disciplines(Some(DisciplineId("wwe2k17".to_owned()))).unwrap();
    /// assert_eq!(wwe2k17_discipline.0.len(), 1);
    /// assert_eq!(wwe2k17_discipline.0.first().unwrap().id,
    /// DisciplineId("wwe2k17".to_owned()));
    /// ```
    pub fn disciplines(&self, id: Option<DisciplineId>) -> Result<Disciplines> {
        let address;
        let id_is_set = id.is_some();
        if let Some(id) = id {
            debug!("Getting disciplines with id: {:?}", id);
            address = Endpoint::DisciplineById(id).to_string();
        } else {
            debug!("Getting all disciplines");
            address = Endpoint::AllDisciplines.to_string();
        }
        let response = request!(self, get, &address)?;
        if id_is_set {
            Ok(Disciplines(vec![serde_json::from_reader::<_, Discipline>(
                response,
            )?]))
        } else {
            Ok(serde_json::from_reader(response)?)
        }
    }

    /// [Returns a collection of public tournaments filtered and sorted by the given query
    /// parameters. A maximum of 20 tournaments will be returned. Only public tournaments are
    /// visible.](https://developer.toornament.com/doc/tournaments#get:tournaments) if id is None or
    /// [a detailed information about one tournament. The tournament must be public.]
    /// (https://developer.toornament.com/doc/tournaments#get:tournaments:id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Getting all tournaments
    /// let all_tournaments: Tournaments = t.tournaments(None, true).unwrap();
    /// // Get tournament by it's id
    /// let tournament = t.tournaments(Some(TournamentId("1".to_owned())), true).unwrap();
    /// assert_eq!(tournament.0.len(), 1);
    /// assert_eq!(tournament.0.first().unwrap().id,
    /// Some(TournamentId("1".to_owned())));
    /// ```
    pub fn tournaments(
        &self,
        tournament_id: Option<TournamentId>,
        with_streams: bool,
    ) -> Result<Tournaments> {
        let address;
        let id_is_set = tournament_id.is_some();
        if let Some(tournament_id) = tournament_id {
            debug!("Getting tournament with id: {:?}", tournament_id);
            address = Endpoint::TournamentByIdGet {
                tournament_id,
                with_streams,
            }
            .to_string();
        } else {
            debug!("Getting all tournaments");
            address = Endpoint::AllTournaments { with_streams }.to_string();
        }
        let response = request!(self, get, &address)?;
        if id_is_set {
            Ok(Tournaments(vec![serde_json::from_reader::<_, Tournament>(
                response,
            )?]))
        } else {
            Ok(serde_json::from_reader(response)?)
        }
    }

    /// [Updates some of the editable information on a tournament.]
    /// (https://developer.toornament.com/doc/tournaments#patch:tournaments:id) if `tournament.id`
    /// is set otherwise [creates a tournament]
    /// (https://developer.toornament.com/doc/tournaments#post:tournaments).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get tournament by it's id
    /// let tournaments = t.tournaments(Some(TournamentId("1".to_owned())), true).unwrap();
    /// assert_eq!(tournaments.0.len(), 1);
    /// let mut tournament = tournaments.0.first().unwrap().clone();
    /// assert_eq!(tournament.id, Some(TournamentId("1".to_owned())));
    /// tournament = tournament.website(Some("https://toornament.com".to_owned()));
    /// // Editing tournament by calling the appropriate method
    /// let tournament = t.edit_tournament(tournament.clone()).unwrap();
    /// assert_eq!(tournament.website,
    /// Some("https://toornament.com".to_owned()));
    /// ```
    pub fn edit_tournament(&self, tournament: Tournament) -> Result<Tournament> {
        let address;
        let id_is_set = tournament.id.is_some();
        if let Some(id) = tournament.id.clone() {
            address = Endpoint::TournamentByIdUpdate(id).to_string();
        } else {
            address = Endpoint::TournamentCreate.to_string();
        }
        let body = serde_json::to_string(&tournament)?;
        let response = if id_is_set {
            debug!("Editing tournament: {:#?}", tournament);
            request_body!(self, patch, &address, body)?
        } else {
            debug!("Creating tournament: {:#?}", tournament);
            request_body!(self, post, &address, body)?
        };
        Ok(serde_json::from_reader(response)?)
    }

    /// [Deletes a tournament, its participants and all its matches]
    /// (https://developer.toornament.com/doc/tournaments#delete:tournaments:id).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Deleting tournament with id = "1"
    /// assert!(t.delete_tournament(TournamentId("1".to_owned())).is_ok());
    /// ```
    pub fn delete_tournament(&self, id: TournamentId) -> Result<()> {
        debug!("Deleting tournament by id: {:?}", id);
        let address = Endpoint::TournamentByIdUpdate(id).to_string();
        let _ = request!(self, delete, &address)?;
        Ok(())
    }

    /// [Returns the private and public tournaments on which the authenticated user has access.
    /// The result is filtered, sorted and paginated by the given query parameters. A maximum of
    /// 50 tournaments is returned (per page).]
    /// (https://developer.toornament.com/doc/tournaments#get:metournaments)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get all my tournaments
    /// let tournaments = t.my_tournaments().unwrap();
    /// ```
    pub fn my_tournaments(&self) -> Result<Tournaments> {
        debug!("Getting all tournaments");
        let address = Endpoint::MyTournaments.to_string();
        let response = request!(self, get, &address)?;
        Ok(serde_json::from_reader(response)?)
    }

    /// [Returns a collection of matches from one tournament. The collection may be filtered and
    /// sorted by optional query parameters. The tournament must be public to have access to its
    /// matches, meaning the tournament organizer has published it.]
    /// (https://developer.toornament.com/doc/matches#get:tournaments:tournament_id:matches)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get all matches of a tournament with id = "1"
    /// let matches = t.matches(TournamentId("1".to_owned()), None, true).unwrap();
    /// // Get match with match id = "2" of a tournament with id = "1"
    /// let matches = t.matches(TournamentId("1".to_owned()), Some(MatchId("2".to_owned())), true).unwrap();
    /// ```
    pub fn matches(
        &self,
        tournament_id: TournamentId,
        match_id: Option<MatchId>,
        with_games: bool,
    ) -> Result<Matches> {
        let response = match match_id {
            Some(match_id) => {
                debug!(
                    "Getting matches by tournament id and match id: {:?} / {:?}",
                    tournament_id, match_id
                );
                let address = Endpoint::MatchByIdGet {
                    tournament_id,
                    match_id,
                    with_games,
                }
                .to_string();
                request!(self, get, &address)?
            }
            None => {
                debug!("Getting matches by tournament id: {:?}", tournament_id);
                let address = Endpoint::MatchesByTournament {
                    tournament_id,
                    with_games,
                }
                .to_string();
                request!(self, get, &address)?
            }
        };

        Ok(serde_json::from_reader(response)?)
    }

    /// [Retrieve a collection of matches from a specific discipline, filtered and sorted by the
    /// given query parameters. It might be a list of matches from different tournaments, but only
    /// from public tournaments. The matches are returned by 20.]
    /// (https://developer.toornament.com/doc/matches#get:tournaments:tournament_id:matches)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get all matches by a discipline with id = "1" with default filter
    /// let matches = t.matches_by_discipline(DisciplineId("1".to_owned()), MatchFilter::default()).unwrap();
    /// ```
    pub fn matches_by_discipline(
        &self,
        discipline_id: DisciplineId,
        filter: MatchFilter,
    ) -> Result<Matches> {
        debug!("Getting matches by discipline id: {:?}", discipline_id);
        let address = Endpoint::MatchesByDiscipline {
            discipline_id,
            filter,
        }
        .to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [If you need to make changes on your match data, you are able to do so by patching one or
    /// several fields of your match.](https://developer.toornament.com/doc/matches#patch:tournaments:tournament_id:matches:id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get a match with id = "2" of a tournament with id = "1"
    /// let matches = t.matches(TournamentId("1".to_owned()),
    ///                         Some(MatchId("2".to_owned())),
    ///                         true).unwrap();
    /// let mut match_to_edit = matches.0.first().unwrap().clone()
    ///                                .number(2u64);
    /// match_to_edit = t.update_match(TournamentId("1".to_owned()),
    ///                                MatchId("2".to_owned()),
    ///                                match_to_edit).unwrap();
    /// assert_eq!(match_to_edit.number, 2u64);
    /// ```
    pub fn update_match(
        &self,
        tournament_id: TournamentId,
        match_id: MatchId,
        updated_match: Match,
    ) -> Result<Match> {
        debug!(
            "Updating a match by tournament id and match id: {:?} / {:?}",
            tournament_id, match_id
        );
        let address = Endpoint::MatchByIdUpdate {
            tournament_id,
            match_id,
        }
        .to_string();
        let body = serde_json::to_string(&updated_match)?;
        let response = request_body!(self, patch, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Returns detailed result about one match.]
    /// (https://developer.toornament.com/doc/matches#get:tournaments:tournament_id:matches:id:result)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get a match result of a match with id = "2" of a tournament with id = "1"
    /// let result = t.match_result(TournamentId("1".to_owned()),
    ///                             MatchId("2".to_owned())).unwrap();
    /// ```
    pub fn match_result(&self, id: TournamentId, match_id: MatchId) -> Result<MatchResult> {
        debug!(
            "Getting match result by tournament id and match id: {:?} / {:?}",
            id, match_id
        );
        let address = Endpoint::MatchResult(id, match_id).to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Update or create detailed result about one match.]
    /// (https://developer.toornament.com/doc/matches#put:tournaments:tournament_id:matches:id:result)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Define a result
    /// let result = MatchResult {
    ///     status: MatchStatus::Completed,
    ///     opponents: Opponents::default(),
    /// };
    /// // Set match result for a match with id = "2" of a tournament with id = "1"
    /// assert!(t.set_match_result(TournamentId("1".to_owned()),
    ///                            MatchId("2".to_owned()),
    ///                            result).is_ok());
    /// ```
    pub fn set_match_result(
        &self,
        id: TournamentId,
        match_id: MatchId,
        result: MatchResult,
    ) -> Result<MatchResult> {
        debug!(
            "Setting match result by tournament id and match id: {:?} / {:?}",
            id, match_id
        );
        let address = Endpoint::MatchResult(id, match_id).to_string();
        let body = serde_json::to_string(&result)?;
        let response = request_body!(self, put, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Returns a collection of games from one match.]
    /// (https://developer.toornament.com/doc/games#get:tournaments:tournament_id:matches:match_id:games)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get match games of a match with id = "2" of a tournament with id = "1"
    /// let games = t.match_games(TournamentId("1".to_owned()),
    ///                           MatchId("2".to_owned()),
    ///                           true).unwrap();
    /// ```
    pub fn match_games(
        &self,
        tournament_id: TournamentId,
        match_id: MatchId,
        with_stats: bool,
    ) -> Result<Games> {
        debug!(
            "Getting match games by tournament id and match id: {:?} / {:?}",
            tournament_id, match_id
        );
        let address = Endpoint::MatchGames {
            tournament_id,
            match_id,
            with_stats,
        }
        .to_string();
        let response = request!(self, get, &address)?;
        Ok(serde_json::from_reader(response)?)
    }

    /// [Returns detailed information about one game.]
    /// (https://developer.toornament.com/doc/games?#get:tournaments:tournament_id:matches:match_id:games:number)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get a match game with number "3" of a match with id = "2" of a tournament with id = "1"
    /// let game = t.match_game(TournamentId("1".to_owned()),
    ///                         MatchId("2".to_owned()),
    ///                         GameNumber(3i64),
    ///                         true).unwrap();
    /// ```
    pub fn match_game(
        &self,
        tournament_id: TournamentId,
        match_id: MatchId,
        game_number: GameNumber,
        with_stats: bool,
    ) -> Result<Game> {
        debug!(
            "Getting match game in details by tournament id and match id: {:?} / {:?}",
            tournament_id, match_id
        );
        let address = Endpoint::MatchGameByNumberGet {
            tournament_id,
            match_id,
            game_number,
            with_stats,
        }
        .to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [If you need to make changes on your game data, you are able to do so by patching one
    /// or several fields of your game.]
    /// (https://developer.toornament.com/doc/games?#patch:tournaments:tournament_id:matches:match_id:games:number)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// let game = Game {
    ///     number: GameNumber(3i64),
    ///     status: MatchStatus::Completed,
    ///     opponents: Opponents::default(),
    /// };
    /// // Update a match game with number "3" of a match with id = "2" of a tournament with id = "1"
    /// assert!(t.update_match_game(TournamentId("1".to_owned()),
    ///                             MatchId("2".to_owned()),
    ///                             GameNumber(3i64),
    ///                             game).is_ok());
    /// ```
    pub fn update_match_game(
        &self,
        tournament_id: TournamentId,
        match_id: MatchId,
        game_number: GameNumber,
        game: Game,
    ) -> Result<Game> {
        debug!(
            "Updating match game by tournament id and match id: {:?} / {:?}",
            tournament_id, match_id
        );
        let address = Endpoint::MatchGameByNumberUpdate {
            tournament_id,
            match_id,
            game_number,
        }
        .to_string();
        let body = serde_json::to_string(&game)?;
        let response = request_body!(self, patch, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Returns detailed result about one specific game.]
    /// (https://developer.toornament.com/doc/games?#get:tournaments:tournament_id:matches:match_id:games:number:result)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get a match game result with number "3" of a match with id = "2" of a tournament with id = "1"
    /// assert!(t.match_game_result(TournamentId("1".to_owned()),
    ///                             MatchId("2".to_owned()),
    ///                             GameNumber(3i64)).is_ok());
    /// ```
    pub fn match_game_result(
        &self,
        tournament_id: TournamentId,
        match_id: MatchId,
        game_number: GameNumber,
    ) -> Result<MatchResult> {
        debug!(
            "Getting match game result by tournament id and match id: {:?} / {:?}",
            tournament_id, match_id
        );
        let address = Endpoint::MatchGameResultGet {
            tournament_id,
            match_id,
            game_number,
        }
        .to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Updates or creates detailed result about one game.]
    /// (https://developer.toornament.com/doc/games?#put:tournaments:tournament_id:matches:match_id:games:number:result)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Define a result
    /// let result = MatchResult {
    ///     status: MatchStatus::Completed,
    ///     opponents: Opponents::default(),
    /// };
    /// // Update a match game result with number "3" of a match with id = "2" of a tournament with id = "1"
    /// assert!(t.update_match_game_result(TournamentId("1".to_owned()),
    ///                                    MatchId("2".to_owned()),
    ///                                    GameNumber(3i64),
    ///                                    result,
    ///                                    true).is_ok());
    /// ```
    pub fn update_match_game_result(
        &self,
        tournament_id: TournamentId,
        match_id: MatchId,
        game_number: GameNumber,
        result: MatchResult,
        update_match: bool,
    ) -> Result<MatchResult> {
        debug!(
            "Setting match game result by tournament id and match id: {:?} / {:?}",
            tournament_id, match_id
        );
        let address = Endpoint::MatchGameResultUpdate {
            tournament_id,
            match_id,
            game_number,
            update_match,
        }
        .to_string();
        let body = serde_json::to_string(&result)?;
        let response = request_body!(self, put, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Returns a collection of participants from one tournament. The tournament must be public
    /// to have access to its participants, meaning the tournament organizer has published it. The
    /// participants are returned by 256.]
    /// (https://developer.toornament.com/doc/participant#get:tournaments:tournament_id:participants)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get participants of a tournament with id = "1" with default filter
    /// let participants = t.tournament_participants(
    ///     TournamentId("1".to_owned()),
    ///     TournamentParticipantsFilter::default()).unwrap();
    /// ```
    pub fn tournament_participants(
        &self,
        tournament_id: TournamentId,
        filter: TournamentParticipantsFilter,
    ) -> Result<Participants> {
        debug!(
            "Getting tournament participants by tournament id: {:?}",
            tournament_id
        );
        let address = Endpoint::Participants {
            tournament_id,
            filter,
        }
        .to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Create a participant in a tournament.]
    /// (https://developer.toornament.com/doc/participants?#post:tournaments:tournament_id:participants)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Define a participant
    /// let participant = Participant::create("Test participant");
    /// // Create a participant for a tournament with id = "1"
    /// let participant = t.create_tournament_participant(TournamentId("1".to_owned()),
    ///                                                   participant).unwrap();
    /// assert!(participant.id.is_some());
    /// ```
    pub fn create_tournament_participant(
        &self,
        id: TournamentId,
        participant: Participant,
    ) -> Result<Participant> {
        debug!("Creating a participant for tournament with id: {:?}", id);
        let address = Endpoint::ParticipantCreate(id).to_string();
        let body = serde_json::to_string(&participant)?;
        let response = request_body!(self, post, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Create a list of participants in a tournament. If any participant already exists he will
    /// be erased.]
    /// (https://developer.toornament.com/doc/participants?_locale=en#put:tournaments:tournament_id:participants)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// let mut participants = vec![Participant::create("First participant"),
    ///                             Participant::create("Second participant")];
    /// // Update a participant for a tournament with id = "1"
    /// let new_participants = t.update_tournament_participants(TournamentId("1".to_owned()),
    ///                                                         Participants(participants)).unwrap();
    /// assert_eq!(new_participants.0.len(), 2);
    /// ```
    pub fn update_tournament_participants(
        &self,
        id: TournamentId,
        participants: Participants,
    ) -> Result<Participants> {
        debug!(
            "Creating a list of participants for tournament with id: {:?}",
            id
        );
        let address = Endpoint::ParticipantsUpdate(id).to_string();
        let body = serde_json::to_string(&participants)?;
        let response = request_body!(self, put, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Returns detailed information about one participant.]
    /// (https://developer.toornament.com/doc/participants?_locale=en#get:tournaments:tournament_id:participants:id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get a participant with id = "2" of a tournament with id = "1"
    /// let participant = t.tournament_participant(TournamentId("1".to_owned()),
    ///                                            ParticipantId("2".to_owned())).unwrap();
    /// assert_eq!(participant.id, Some(ParticipantId("2".to_owned())));
    /// ```
    pub fn tournament_participant(
        &self,
        id: TournamentId,
        participant_id: ParticipantId,
    ) -> Result<Participant> {
        debug!(
            "Getting tournament participant by tournament id and participant id: {:?} / {:?}",
            id, participant_id
        );
        let address = Endpoint::ParticipantById(id, participant_id).to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Update some of the editable information on a participant.]
    /// (https://developer.toornament.com/doc/participants?_locale=en#patch:tournaments:tournament_id:participants:id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get a participant with id = "2" of a tournament with id = "1"
    /// let mut participant = t.tournament_participant(TournamentId("1".to_owned()),
    ///                                                ParticipantId("2".to_owned())).unwrap();
    /// assert_eq!(participant.id, Some(ParticipantId("2".to_owned())));
    /// // Update the participant's name and send it
    /// participant = participant.name("Updated participant name here".to_owned());
    /// let updated_participant = t.update_tournament_participant(
    ///     TournamentId("1".to_owned()),
    ///     ParticipantId("2".to_owned()),
    ///     participant).unwrap();
    /// assert_eq!(updated_participant.id, Some(ParticipantId("2".to_owned())));
    /// assert_eq!(updated_participant.name, "Updated participant name here");
    /// ```
    pub fn update_tournament_participant(
        &self,
        id: TournamentId,
        participant_id: ParticipantId,
        participant: Participant,
    ) -> Result<Participant> {
        debug!(
            "Updating a participant for tournament with id and participant id: {:?} / {:?}",
            id, participant_id
        );
        let address = Endpoint::ParticipantById(id, participant_id).to_string();
        let body = serde_json::to_string(&participant)?;
        let response = request_body!(self, patch, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Deletes one participant.]
    /// (https://developer.toornament.com/doc/participants?_locale=en#delete:tournaments:tournament_id:participants:id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Delete a participant with id = "2" of a tournament with id = "1"
    /// assert!(t.delete_tournament_participant(TournamentId("1".to_owned()),
    ///                                         ParticipantId("2".to_owned())).is_ok());
    /// ```
    pub fn delete_tournament_participant(
        &self,
        id: TournamentId,
        participant_id: ParticipantId,
    ) -> Result<()> {
        debug!(
            "Deleting a participant for tournament with id and participant id: {:?} / {:?}",
            id, participant_id
        );
        let address = Endpoint::ParticipantById(id, participant_id).to_string();
        let response = request!(self, delete, &address)?;
        if response.status().is_success() {
            Ok(())
        } else {
            Err(Error::Rest("Something went wrong"))
        }
    }

    /// [Returns a collection of permission from one tournament.]
    /// (https://developer.toornament.com/doc/permissions?_locale=en#get:tournaments:tournament_id:permissions)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get permissions of a tournament with id = "1"
    /// let permissions = t.tournament_permissions(TournamentId("1".to_owned())).unwrap();
    /// ```
    pub fn tournament_permissions(&self, id: TournamentId) -> Result<Permissions> {
        debug!("Getting tournament permissions by tournament id: {:?}", id);
        let address = Endpoint::Permissions(id).to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Create a permission for a user on a tournament.]
    /// (https://developer.toornament.com/doc/permissions?_locale=en#post:tournaments:tournament_id:permissions)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// use std::collections::BTreeSet;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Define our permission
    /// let mut attributes = BTreeSet::new();
    /// attributes.insert(PermissionAttribute::Register);
    /// attributes.insert(PermissionAttribute::Edit);
    ///
    /// let permission = Permission::create("test@mail.ru", PermissionAttributes(attributes));
    /// // Add permission to a tournament with id = "1"
    /// let new_permission = t.create_tournament_permission(TournamentId("1".to_owned()),
    ///                                                     permission).unwrap();
    /// assert!(new_permission.id.is_some());
    /// assert_eq!(new_permission.email, "test@mail.ru");
    /// assert_eq!(new_permission.attributes.0.len(), 2);
    /// ```
    pub fn create_tournament_permission(
        &self,
        id: TournamentId,
        permission: Permission,
    ) -> Result<Permission> {
        debug!("Creating tournament permissions by tournament id: {:?}", id);
        let address = Endpoint::Permissions(id).to_string();
        let body = serde_json::to_string(&permission)?;
        let response = request_body!(self, post, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Retrieves a permission of a tournament.]
    /// (https://developer.toornament.com/doc/permissions?_locale=en#get:tournaments:tournament_id:permissions:permission_id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// use std::collections::BTreeSet;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get a permission with id = "2" of a tournament with id = "1"
    /// let permission = t.tournament_permission(TournamentId("1".to_owned()),
    ///                                          PermissionId("2".to_owned())).unwrap();
    /// assert_eq!(permission.id, Some(PermissionId("2".to_owned())));
    /// ```
    pub fn tournament_permission(
        &self,
        id: TournamentId,
        permission_id: PermissionId,
    ) -> Result<Permission> {
        debug!(
            "Getting tournament permission by tournament id and permission id: {:?} / {:?}",
            id, permission_id
        );
        let address = Endpoint::PermissionById(id, permission_id).to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Update rights of a permission.]
    /// (https://developer.toornament.com/doc/permissions?_locale=en#patch:tournaments:tournament_id:permissions:permission_id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// use std::collections::BTreeSet;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Define our permission attributes
    /// let mut attributes = BTreeSet::new();
    /// attributes.insert(PermissionAttribute::Register);
    /// attributes.insert(PermissionAttribute::Edit);
    ///
    /// // Update attributes of a permission with id = "2" of a tournament with id = "1"
    /// let permission = t.update_tournament_permission_attributes(
    ///     TournamentId("1".to_owned()),
    ///     PermissionId("2".to_owned()),
    ///     PermissionAttributes(attributes)).unwrap();
    /// assert_eq!(permission.id, Some(PermissionId("2".to_owned())));
    /// assert_eq!(permission.attributes.0.len(), 2);
    /// assert!(permission.attributes.0.iter().find(|p| *p == &PermissionAttribute::Edit).is_some());
    /// assert!(permission.attributes.0.iter().find(|p| *p == &PermissionAttribute::Register).is_some());
    /// ```
    pub fn update_tournament_permission_attributes(
        &self,
        id: TournamentId,
        permission_id: PermissionId,
        attributes: PermissionAttributes,
    ) -> Result<Permission> {
        #[derive(Serialize)]
        struct WrappedAttributes {
            attributes: PermissionAttributes,
        }
        debug!(
            "Updating tournament permission attributes by tournament id \
             and permission id: {:?} / {:?}",
            id, permission_id
        );
        let address = Endpoint::PermissionById(id, permission_id).to_string();
        let wrapped_attributes = WrappedAttributes { attributes };
        let body = serde_json::to_string(&wrapped_attributes)?;
        let response = request_body!(self, patch, &address, body)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Delete a user permission of a tournament.]
    /// (https://developer.toornament.com/doc/permissions?_locale=en#delete:tournaments:tournament_id:permissions:permission_id)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// use std::collections::BTreeSet;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Delete a permission with id = "2" of a tournament with id = "1"
    /// assert!(t.delete_tournament_permission(
    ///     TournamentId("1".to_owned()),
    ///     PermissionId("2".to_owned())).is_ok());
    /// ```
    pub fn delete_tournament_permission(
        &self,
        id: TournamentId,
        permission_id: PermissionId,
    ) -> Result<()> {
        debug!(
            "Deleting a permission for tournament with id and permission id: {:?} / {:?}",
            id, permission_id
        );
        let address = Endpoint::PermissionById(id, permission_id).to_string();
        let response = request!(self, delete, &address)?;
        if response.status().is_success() {
            Ok(())
        } else {
            Err(Error::Rest("Something went wrong"))
        }
    }

    /// [Returns a collection of stages from one tournament. The tournament must be public to have
    /// access to its stages, meaning the tournament organizer must publish it.]
    /// (https://developer.toornament.com/doc/stages?_locale=en#get:tournaments:tournament_id:stages)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// use std::collections::BTreeSet;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get stages of a tournament with id = "1"
    /// let stages = t.tournament_stages(TournamentId("1".to_owned())).unwrap();
    /// ```
    pub fn tournament_stages(&self, id: TournamentId) -> Result<Stages> {
        debug!("Getting tournament stages by tournament id: {:?}", id);
        let address = Endpoint::Stages(id).to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }

    /// [Returns a collection of videos from one tournament. The collection may be filtered and
    /// sorted by optional query parameters. The tournament must be public to have access to its
    /// videos, meaning the tournament organizer has published it. The videos are returned by 20.]
    /// (https://developer.toornament.com/doc/videos?_locale=en#get:tournaments:tournament_id:videos)
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toornament::*;
    /// use std::collections::BTreeSet;
    /// let t = Toornament::with_application("API_TOKEN",
    ///                                      "CLIENT_ID",
    ///                                      "CLIENT_SECRET").unwrap();
    /// // Get videos of a tournament with id = "1" with default filter
    /// let videos = t.tournament_videos(TournamentId("1".to_owned()),
    ///                                  TournamentVideosFilter::default()).unwrap();
    /// ```
    pub fn tournament_videos(
        &self,
        tournament_id: TournamentId,
        filter: TournamentVideosFilter,
    ) -> Result<Videos> {
        debug!(
            "Getting tournament videos by tournament id: {:?}",
            tournament_id
        );
        let address = Endpoint::Videos {
            tournament_id,
            filter,
        }
        .to_string();
        let response = request!(self, get, &address)?;

        Ok(serde_json::from_reader(response)?)
    }
}

#[cfg(test)]
mod tests {
    fn assert_sync_and_send<T: Sync + Send>() {}

    #[test]
    fn test_sync_and_send() {
        assert_sync_and_send::<::Toornament>();
    }
}