use std::{num::NonZero, ops::Not};
use serde::Serialize;
#[cfg(feature = "blocking")]
use crate::helpers::make_request_blocking;
use crate::{Result, helpers::make_request, types::Season};
use super::BestTimeLeaderboard;
const BASE_URL: &str = "https://api.mcsrranked.com/record-leaderboard";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BestTimeSeason {
All,
Current,
Specific(NonZero<Season>),
}
impl BestTimeSeason {
fn is_all(&self) -> bool {
matches!(self, BestTimeSeason::All)
}
}
impl Serialize for BestTimeSeason {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use BestTimeSeason as BTS;
serde::Serialize::serialize(
&match self {
BTS::All => None,
BTS::Current => Some(0),
BTS::Specific(season) => Some(season.get()),
},
serializer,
)
}
}
impl From<Season> for BestTimeSeason {
fn from(value: Season) -> Self {
use BestTimeSeason as BTS;
match NonZero::new(value) {
None => BTS::Current,
Some(v) => BTS::Specific(v),
}
}
}
impl From<Option<Season>> for BestTimeSeason {
fn from(value: Option<Season>) -> Self {
use BestTimeSeason as BTS;
match value {
None => BTS::All,
Some(season) => Self::from(season),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GetBestTimeLeaderboardParams {
#[serde(skip_serializing_if = "BestTimeSeason::is_all")]
pub season: BestTimeSeason,
#[serde(skip_serializing_if = "Not::not")]
pub distinct: bool,
}
impl Default for GetBestTimeLeaderboardParams {
fn default() -> Self {
Self {
season: BestTimeSeason::All,
distinct: false,
}
}
}
impl GetBestTimeLeaderboardParams {
pub fn new(season: impl Into<BestTimeSeason>, distinct: bool) -> Self {
Self {
season: season.into(),
distinct,
}
}
pub fn season(mut self, season: impl Into<BestTimeSeason>) -> Self {
self.season = season.into();
self
}
pub fn distinct(mut self, distinct: bool) -> Self {
self.distinct = distinct;
self
}
}
impl BestTimeLeaderboard {
pub async fn get<'a>(
params: impl Into<Option<&'a GetBestTimeLeaderboardParams>>,
) -> Result<Self> {
make_request(BASE_URL, &[] as &[&str], params.into()).await
}
}
#[cfg(feature = "blocking")]
impl BestTimeLeaderboard {
pub fn get_blocking<'a>(
params: impl Into<Option<&'a GetBestTimeLeaderboardParams>>,
) -> Result<Self> {
make_request_blocking(BASE_URL, &[] as &[&str], params.into())
}
}