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
//! Models for the `/players/:tag` API endpoint.
//! Included by the feature `"players"`; removing that feature will disable the usage of this module.

use serde::{self, Serialize, Deserialize};


#[cfg(feature = "async")]


#[cfg(feature = "async")]
use crate::util::a_fetch_route;

#[cfg(feature = "async")]
use async_trait::async_trait;

use crate::traits::{FetchFrom, PropFetchable, GetFetchProp};
use crate::error::{Result};

#[cfg(feature = "clubs")]
use super::super::clubs::ClubMember;

use crate::http::Client;
use crate::http::routes::Route;
use crate::util::{auto_hashtag, fetch_route};
use crate::serde::{deserialize_number_from_string, one_default, oxffffff_default};

use super::super::common::StarPower;

use super::battlelog::{BattlePlayer};

#[cfg(feature = "rankings")]
use crate::PlayerRanking;

/// A struct representing a Brawl Stars player, with all of its data.
/// Use [`Player::fetch`] to fetch one based on tag. (Make sure the [`PropFetchable`] trait
/// is imported - in general, it is recommended to **at least** `use brawl_api::traits::*`, or,
/// even, `use brawl_api::prelude::*` to bring the models into scope as well.)
///
/// [`PropFetchable`]: traits/trait.PropFetchable.html
/// [`Player::fetch`]: ./struct.Player.html#method.fetch
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Player {

    /// The club the Player is in (as a [`PlayerClub`] instance), or None if none.
    ///
    /// [`PlayerClub`]: ./struct.PlayerClub.html
    #[serde(default)]
    pub club: Option<PlayerClub>,

    /// Whether or not the Player was qualified from the Championship challenge (2020).
    #[serde(default = "false_default")]
    pub is_qualified_from_championship_challenge: bool,

    /// Amount of 3v3 victories the Player has earned.
    #[serde(rename = "3vs3Victories")]
    pub tvt_victories: usize,

    /// The player's tag. **Note: this includes the initial '#'.**
    #[serde(default)]
    pub tag: String,

    /// The player's name.
    #[serde(default)]
    pub name: String,

    /// The player's current trophies.
    #[serde(default)]  // zero
    pub trophies: usize,

    /// The player's highest trophies amount.
    #[serde(default)]  // zero
    pub highest_trophies: usize,

    /// The player's experience level.
    #[serde(default = "one_default")]
    pub exp_level: usize,

    /// The player's experience points.
    #[serde(default)]  // zero
    pub exp_points: usize,

    /// The player's current power play points.
    #[serde(default)]  // zero
    pub power_play_points: usize,

    /// The player's highest power play points.
    #[serde(default)]  // zero
    pub highest_power_play_points: usize,

    /// The player's victories in solo showdown (how many times ranked #1).
    #[serde(default)]  // zero
    pub solo_victories: usize,

    /// The player's victories in duo showdown (how many times ranked #1).
    #[serde(default)]  // zero
    pub duo_victories: usize,

    /// The player's best Robo Rumble time, in seconds.
    #[serde(default)]  // zero
    pub best_robo_rumble_time: usize,

    /// The player's best time as a Big Brawler, in seconds.
    #[serde(default)]  // zero
    pub best_time_as_big_brawler: usize,

    /// The player's brawlers.
    #[serde(default)]
    pub brawlers: Vec<PlayerBrawlerStat>,

    /// The player's name color, as an integer (Default is 0xffffff = 16777215 - this is used
    /// when the data is not available).
    #[serde(default = "oxffffff_default")]
    #[serde(deserialize_with = "deserialize_number_from_string")]  // parse num
    pub name_color: u64,
}
fn false_default() -> bool { false }

impl Default for Player {
    
    /// Initializes a Player instance with default values for each field.
    fn default() -> Player {
        Player {
            club: None,

            is_qualified_from_championship_challenge: false,

            tvt_victories: 0,

            tag: String::from(""),

            name: String::from(""),

            trophies: 0,

            highest_trophies: 0,

            exp_level: 1,

            exp_points: 0,

            power_play_points: 0,

            highest_power_play_points: 0,

            solo_victories: 0,

            duo_victories: 0,

            best_robo_rumble_time: 0,

            best_time_as_big_brawler: 0,

            brawlers: Vec::<PlayerBrawlerStat>::new(),

            name_color: 0xff_ff_ff,
        }
    }
}

impl GetFetchProp for Player {
    type Property = str;

    fn get_fetch_prop(&self) -> &str { &*self.tag }

    fn get_route(tag: &str) -> Route { Route::Player(auto_hashtag(tag)) }
}

#[cfg_attr(feature = "async", async_trait)]
impl PropFetchable for Player {
    type Property = str;

    /// (Sync) Fetches a player from its tag.
    ///
    /// # Errors
    ///
    /// This function may error:
    /// - While requesting (will return an [`Error::Request`]);
    /// - After receiving a bad status code (API or other error - returns an [`Error::Status`]);
    /// - After a ratelimit is indicated by the API, while also specifying when it is lifted ([`Error::Ratelimited`]);
    /// - While parsing incoming JSON (will return an [`Error::Json`]).
    ///
    /// (All of those, of course, wrapped inside an `Err`.)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use brawl_api::{Client, Player, traits::*};
    ///
    /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let my_client = Client::new("my auth token");
    /// let player = Player::fetch(&my_client, "#PLAYERTAGHERE")?;
    /// // now the data for the given player is available for use
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Error::Request`]: error/enum.Error.html#variant.Request
    /// [`Error::Status`]: error/enum.Error.html#variant.Status
    /// [`Error::Ratelimited`]: error/enum.Error.html#variant.Ratelimited
    /// [`Error::Json`]: error/enum.Error.html#variant.Json
    fn fetch(client: &Client, tag: &str) -> Result<Player> {
        let route = Self::get_route(tag);
        fetch_route::<Player>(client, &route)
    }

    /// (Async) Fetches a player from its tag.
    ///
    /// # Errors
    ///
    /// This function may error:
    /// - While requesting (will return an [`Error::Request`]);
    /// - After receiving a bad status code (API or other error - returns an [`Error::Status`]);
    /// - After a ratelimit is indicated by the API, while also specifying when it is lifted ([`Error::Ratelimited`]);
    /// - While parsing incoming JSON (will return an [`Error::Json`]).
    ///
    /// (All of those, of course, wrapped inside an `Err`.)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use brawl_api::{Client, Player, traits::*};
    ///
    /// # async fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let my_client = Client::new("my auth token");
    /// let player = Player::a_fetch(&my_client, "#PLAYERTAGHERE").await?;
    /// // now the data for the given player is available for use
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Error::Request`]: error/enum.Error.html#variant.Request
    /// [`Error::Status`]: error/enum.Error.html#variant.Status
    /// [`Error::Ratelimited`]: error/enum.Error.html#variant.Ratelimited
    /// [`Error::Json`]: error/enum.Error.html#variant.Json
    #[cfg(feature="async")]
    async fn a_fetch(client: &Client, tag: &'async_trait str) -> Result<Player>
        where Self: 'async_trait,
              Self::Property: 'async_trait,
    {
        let route = Player::get_route(&tag);
        a_fetch_route::<Player>(client, &route).await
    }
}

#[cfg_attr(feature = "async", async_trait)]
#[cfg(feature = "clubs")]
impl FetchFrom<ClubMember> for Player {
    /// (Sync) Fetches a `Player` instance, given a preexisting `ClubMember` instance.
    ///
    /// # Errors
    ///
    /// See [`Player::fetch`].
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use brawl_api::{Client, Player, Club, traits::*};
    ///
    /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let my_client = Client::new("my auth token");
    /// let club = Club::fetch(&my_client, "#CLUB_TAG_HERE")?;
    /// let some_member = &club.members[0];
    /// let some_player = Player::fetch_from(&my_client, some_member)?;
    /// // now `some_member`'s full data, as a Player, is available for use.
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Player::fetch`]: struct.Player.html#method.fetch
    fn fetch_from(client: &Client, member: &ClubMember) -> Result<Player> {
        Player::fetch(client, &member.tag)
    }

    /// (Async) Fetches a `Player` instance, given a preexisting `ClubMember` instance.
    ///
    /// # Errors
    ///
    /// See [`Player::fetch`].
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use brawl_api::{Client, Player, Club, traits::*};
    ///
    /// # async fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let my_client = Client::new("my auth token");
    /// let club = Club::a_fetch(&my_client, "#CLUB_TAG_HERE").await?;
    /// let some_member = &club.members[0];
    /// let some_player = Player::a_fetch_from(&my_client, some_member).await?;
    /// // now `some_member`'s full data, as a Player, is available for use.
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Player::fetch`]: struct.Player.html#method.fetch
    #[cfg(feature = "async")]
    async fn a_fetch_from(client: &Client, member: &ClubMember) -> Result<Player> {
        Player::a_fetch(client, &member.tag).await
    }
}

#[cfg_attr(feature = "async", async_trait)]
impl FetchFrom<BattlePlayer> for Player {
    /// (Async) Fetches a `Player` instance, given a preexisting `BattlePlayer` instance.
    ///
    /// # Errors
    ///
    /// See [`Player::fetch`].
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use brawl_api::{
    ///     Client, Player, BattleLog, Battle, BattleResultInfo, BattlePlayer,
    ///     traits::*
    /// };
    ///
    /// # fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let my_client = Client::new("my auth token");
    /// let battlelog = BattleLog::fetch(&my_client, "#PLAYER_TAG_HERE")?;
    /// let most_recent_battle: Option<&Battle> = battlelog.get(0);
    ///
    /// if let Some(battle) = most_recent_battle {
    ///     if let Some(ref teams) = &battle.result.teams {
    ///         let some_b_player: &BattlePlayer = &teams[0][0];
    ///         let some_player = Player::fetch_from(&my_client, some_b_player)?;
    ///         // now `some_b_player`'s full data, as a Player, is available for use.
    ///     }
    /// }
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Player::fetch`]: struct.Player.html#method.fetch
    fn fetch_from(client: &Client, b_player: &BattlePlayer) -> Result<Player> {
        Player::fetch(client, &b_player.tag)
    }

    /// (Async) Fetches a `Player` instance, given a preexisting `BattlePlayer` instance.
    ///
    /// # Errors
    ///
    /// See [`Player::fetch`].
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use brawl_api::{
    ///     Client, Player, BattleLog, Battle, BattleResultInfo, BattlePlayer,
    ///     traits::*
    /// };
    ///
    /// # async fn main() -> Result<(), Box<dyn ::std::error::Error>> {
    /// let my_client = Client::new("my auth token");
    /// let battlelog = BattleLog::a_fetch(&my_client, "#PLAYER_TAG_HERE").await?;
    /// let most_recent_battle: Option<&Battle> = battlelog.get(0);
    ///
    /// if let Some(battle) = most_recent_battle {
    ///     if let Some(ref teams) = &battle.result.teams {
    ///         let some_b_player: &BattlePlayer = &teams[0][0];
    ///         let some_player = Player::a_fetch_from(&my_client, some_b_player).await?;
    ///         // now `some_b_player`'s full data, as a Player, is available for use.
    ///     }
    /// }
    ///
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`Player::fetch`]: struct.Player.html#method.fetch
    #[cfg(feature = "async")]
    async fn a_fetch_from(client: &Client, b_player: &BattlePlayer) -> Result<Player> {
        Player::a_fetch(client, &b_player.tag).await
    }
}

#[cfg_attr(feature = "async", async_trait)]
#[cfg(feature = "rankings")]
impl FetchFrom<PlayerRanking> for Player {

    /// (Sync) Fetches a `Player` using data from a [`PlayerRanking`] object.
    ///
    /// [`PlayerRanking`]: ../../rankings/players/struct.PlayerRanking.html
    fn fetch_from(client: &Client, p_ranking: &PlayerRanking) -> Result<Player> {
        Player::fetch(client, &p_ranking.tag)
    }

    /// (Async) Fetches a `Player` using data from a [`PlayerRanking`] object.
    ///
    /// [`PlayerRanking`]: ../../rankings/players/struct.PlayerRanking.html
    #[cfg(feature = "async")]
    async fn a_fetch_from(client: &Client, p_ranking: &PlayerRanking) -> Result<Player> {
        Player::a_fetch(client, &p_ranking.tag).await
    }
}


/// A struct representing a club obtained from [`Player.club`].
/// Note that it does not contain all of a club's information.
/// For that, use [`Club::fetch_from`] (fetches the full Club).
///
/// [`Player.club`]: ./struct.Player.html#structfield.club
/// [`Club::fetch_from`]: ../clubs/struct.Club.html#method.fetch_from
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlayerClub {

    /// The club's tag.
    #[serde(default)]
    pub tag: String,

    /// The club's name
    #[serde(default)]
    pub name: String
}

impl Default for PlayerClub {

    /// Returns an instance of `PlayerClub` with initial values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brawl_api::PlayerClub;
    ///
    /// assert_eq!(
    ///     PlayerClub::default(),
    ///     PlayerClub {
    ///         tag: String::from(""),
    ///         name: String::from(""),
    ///     }
    /// );
    /// ```
    fn default() -> PlayerClub {
        PlayerClub {
            tag: String::from(""),
            name: String::from("")
        }
    }
}

/// A struct containing information about a player's brawler (see [`Player.brawlers`]).
///
/// [`Player.brawlers`]: ./struct.Player.html#structfield.brawlers
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlayerBrawlerStat {

    /// A vector containing the brawler's star powers (represented by [`StarPower`]),
    /// if any (otherwise empty vector).
    ///
    /// [`StarPower`]: ./struct.StarPower.html
    #[serde(default)]
    pub star_powers: Vec<StarPower>,

    /// The brawler's id (an arbitrary number).
    #[serde(default)]  // zero
    pub id: usize,

    /// The brawler's rank.
    #[serde(default = "one_default")]
    pub rank: u16,

    /// The brawler's trophies.
    #[serde(default)]
    pub trophies: usize,

    /// The brawler's highest trophies amount.
    #[serde(default)]  // zero
    pub highest_trophies: usize,

    /// The brawler's power (1-10).
    #[serde(default = "one_default")]
    pub power: u8,

    /// The brawler's name.
    #[serde(default)]
    pub name: String,
}

impl Default for PlayerBrawlerStat {
    
    /// Initializes a new BrawlerStat instance, with default values.
    fn default() -> PlayerBrawlerStat {
        PlayerBrawlerStat {
            star_powers: vec![],
            id: 0,
            rank: 1,
            trophies: 0,
            highest_trophies: 0,
            power: 1,
            name: String::from(""),
        }
    }
}

///////////////////////////////////   tests   ///////////////////////////////////

#[cfg(test)]
mod tests {
    use std::result::Result as StdResult;
    use super::{Player, PlayerClub, PlayerBrawlerStat, StarPower};
    use crate::error::Error as BrawlError;
    use serde_json;

    /// Tests for player deserialization from API-provided JSON.
    #[test]
    fn players_deser() -> StdResult<(), Box<dyn ::std::error::Error>> {
        let player_json_s = r##"{
  "tag": "#CCCCCC",
  "name": "User",
  "nameColor": "0xff1ba5f5",
  "trophies": 13370,
  "highestTrophies": 30000,
  "powerPlayPoints": 200,
  "highestPowerPlayPoints": 900,
  "expLevel": 100,
  "expPoints": 70000,
  "isQualifiedFromChampionshipChallenge": false,
  "3vs3Victories": 3333,
  "soloVictories": 999,
  "duoVictories": 333,
  "bestRoboRumbleTime": 350,
  "bestTimeAsBigBrawler": 250,
  "club": {
    "tag": "#888888",
    "name": "Club"
  },
  "brawlers": [
    {
      "id": 16000000,
      "name": "SHELLY",
      "power": 9,
      "rank": 20,
      "trophies": 500,
      "highestTrophies": 549,
      "starPowers": []
    },
    {
      "id": 16000001,
      "name": "COLT",
      "power": 10,
      "rank": 18,
      "trophies": 420,
      "highestTrophies": 440,
      "starPowers": [
        {
          "id": 23000138,
          "name": "Magnum Special"
        },
        {
          "id": 23000077,
          "name": "Slick Boots"
        }
      ]
    }
  ]
}"##;
        let player: Player = serde_json::from_str::<Player>(player_json_s)
            .map_err(BrawlError::Json)?;

        assert_eq!(
            player,
            Player {
                tag: String::from("#CCCCCC"),
                name: String::from("User"),
                name_color: 0xff1ba5f5,
                trophies: 13370,
                highest_trophies: 30000,
                power_play_points: 200,
                highest_power_play_points: 900,
                exp_level: 100,
                exp_points: 70000,
                is_qualified_from_championship_challenge: false,
                tvt_victories: 3333,
                solo_victories: 999,
                duo_victories: 333,
                best_robo_rumble_time: 350,
                best_time_as_big_brawler: 250,
                club: Some(PlayerClub {
                    tag: String::from("#888888"),
                    name: String::from("Club")
                }),
                brawlers: vec![
                    PlayerBrawlerStat {
                        id: 16000000,
                        name: String::from("SHELLY"),
                        power: 9,
                        rank: 20,
                        trophies: 500,
                        highest_trophies: 549,
                        star_powers: vec![]
                    },
                    PlayerBrawlerStat {
                        id: 16000001,
                        name: String::from("COLT"),
                        power: 10,
                        rank: 18,
                        trophies: 420,
                        highest_trophies: 440,
                        star_powers: vec![
                            StarPower {
                                id: 23000138,
                                name: String::from("Magnum Special")
                            },
                            StarPower {
                                id: 23000077,
                                name: String::from("Slick Boots")
                            }
                        ]
                    },
                ]
            }
        );
        Ok(())
    }
}