use super::RemindType;
use crate::models::{HasId, HasName, Member, Snowflake};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Schedule {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub id: Snowflake,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub description: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub start_timestamp: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub end_timestamp: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub jump_channel_id: Snowflake,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub remind_type: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub creator: Option<Member>,
}
impl Schedule {
pub fn new(
name: impl Into<String>,
start_timestamp: impl Into<String>,
end_timestamp: impl Into<String>,
jump_channel_id: Option<String>,
remind_type: RemindType,
) -> Self {
Self {
id: String::new(),
name: name.into(),
description: String::new(),
start_timestamp: start_timestamp.into(),
end_timestamp: end_timestamp.into(),
jump_channel_id: jump_channel_id.unwrap_or_default(),
remind_type: remind_type.to_wire_string(),
creator: None,
}
}
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = description.into();
self
}
pub fn with_creator(mut self, creator: Member) -> Self {
self.creator = Some(creator);
self
}
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.id = id.into();
self
}
pub fn has_reminder(&self) -> bool {
!self.remind_type.is_empty() && self.remind_type != "0"
}
pub fn reminder_description(&self) -> &'static str {
self.remind_type
.parse::<u8>()
.map(RemindType::from)
.map(|remind_type| remind_type.description())
.unwrap_or("No reminder")
}
pub fn start_timestamp_parsed(&self) -> Result<i64, std::num::ParseIntError> {
self.start_timestamp.parse::<i64>()
}
pub fn end_timestamp_parsed(&self) -> Result<i64, std::num::ParseIntError> {
self.end_timestamp.parse::<i64>()
}
pub fn duration_seconds(&self) -> Option<i64> {
let start = self.start_timestamp_parsed().ok()?;
let end = self.end_timestamp_parsed().ok()?;
Some(end - start)
}
pub fn has_jump_channel(&self) -> bool {
!self.jump_channel_id.is_empty()
}
}
impl HasId for Schedule {
fn id(&self) -> Option<&Snowflake> {
(!self.id.is_empty()).then_some(&self.id)
}
}
impl HasName for Schedule {
fn name(&self) -> &str {
&self.name
}
}
impl std::fmt::Display for Schedule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Schedule {{ id: {:?}, name: {}, start: {}, end: {}, reminder: {} }}",
self.id(),
self.name,
self.start_timestamp,
self.end_timestamp,
self.reminder_description()
)
}
}