use std::sync::Arc;
use serde_json::{Value, json};
use url::Url;
use crate::envelope::Envelope;
use crate::error::Error;
use crate::links;
use crate::routes::{self, Resource};
use crate::transport::{RequestBody, Transport};
const ALL_DAYS: &[&str] = &[
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
];
const WEEKDAYS: &[&str] = &["monday", "tuesday", "wednesday", "thursday", "friday"];
const WEEKEND: &[&str] = &["saturday", "sunday"];
const SCHEDULE_FAMILY: &str = "networks/{id}/profiles/{id}/schedules/{id}";
const BARE_ID_MESSAGE: &str =
"must be the schedule's path, absolute URL or envelope; a bare id cannot be resolved";
#[derive(Debug, Default, Clone)]
pub struct UpdateScheduleOptions<'a> {
pub name: Option<&'a str>,
pub days: Option<&'a [&'a str]>,
pub start: Option<&'a str>,
pub end: Option<&'a str>,
pub enabled: Option<bool>,
}
#[derive(Debug)]
pub struct ScheduleApi {
transport: Arc<Transport>,
}
impl ScheduleApi {
#[must_use]
pub fn new(transport: Arc<Transport>) -> Self {
Self { transport }
}
fn resolve_schedule_url(
&self,
route: &Resource,
id_or_url: &str,
parent: Option<&Value>,
) -> Result<Url, Error> {
let host = self.transport.api_host();
if let Some(parent) = parent {
return links::self_url(host, parent)?.ok_or_else(|| {
Error::validation("schedule", "envelope has no resolvable 'url' field")
});
}
if !is_path_or_url(id_or_url) {
return Err(Error::validation("schedule", BARE_ID_MESSAGE));
}
let url = route.resolve(host, id_or_url, None)?;
links::require_family_path(
id_or_url.trim_end_matches('/'),
SCHEDULE_FAMILY,
"",
"schedule",
)?;
Ok(url)
}
pub async fn get_schedules(
&self,
network_id: &str,
profile_id: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.transport
.nested(
&routes::schedule::SCHEDULE_GET_SCHEDULES,
network_id,
profile_id,
parent,
&[],
RequestBody::None,
)
.await
}
#[allow(clippy::too_many_arguments)] pub async fn create_schedule(
&self,
network_id: &str,
profile_id: &str,
name: &str,
days: &[&str],
start: &str,
end: &str,
enabled: bool,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let url = routes::schedule::SCHEDULE_CREATE_SCHEDULE.resolve(
self.transport.api_host(),
network_id,
profile_id,
parent,
)?;
links::warn_uncharacterised_write("create_schedule");
self.transport
.request(
routes::schedule::SCHEDULE_CREATE_SCHEDULE.method.clone(),
url,
&[],
RequestBody::Json(json!({
"name": name,
"days": days,
"start": start,
"end": end,
"enabled": enabled,
})),
)
.await
}
pub async fn update_schedule(
&self,
schedule: &str,
options: &UpdateScheduleOptions<'_>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let mut payload = serde_json::Map::new();
if let Some(name) = options.name {
payload.insert("name".to_owned(), Value::String(name.to_owned()));
}
if let Some(days) = options.days {
payload.insert(
"days".to_owned(),
Value::Array(
days.iter()
.map(|d| Value::String((*d).to_owned()))
.collect(),
),
);
}
if let Some(start) = options.start {
payload.insert("start".to_owned(), Value::String(start.to_owned()));
}
if let Some(end) = options.end {
payload.insert("end".to_owned(), Value::String(end.to_owned()));
}
if let Some(enabled) = options.enabled {
payload.insert("enabled".to_owned(), Value::Bool(enabled));
}
if payload.is_empty() {
return Err(Error::validation(
"schedule",
"at least one of name, days, start, end, enabled must be supplied",
));
}
let url =
self.resolve_schedule_url(&routes::schedule::SCHEDULE_UPDATE, schedule, parent)?;
links::warn_uncharacterised_write("update_schedule");
self.transport
.request(
routes::schedule::SCHEDULE_UPDATE.method.clone(),
url,
&[],
RequestBody::Json(Value::Object(payload)),
)
.await
}
pub async fn delete_schedule(
&self,
schedule: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let url =
self.resolve_schedule_url(&routes::schedule::SCHEDULE_DELETE, schedule, parent)?;
links::warn_uncharacterised_write("delete_schedule");
self.transport
.request(
routes::schedule::SCHEDULE_DELETE.method.clone(),
url,
&[],
RequestBody::None,
)
.await
}
pub async fn clear_profile_schedule(
&self,
network_id: &str,
profile_id: &str,
parent: Option<&Value>,
) -> Result<Vec<Envelope>, Error> {
let schedules_response = self.get_schedules(network_id, profile_id, parent).await?;
let data = schedules_response.data();
let pauses: &[Value] = data.as_array().map_or(&[], Vec::as_slice);
let mut results = Vec::with_capacity(pauses.len());
for pause in pauses {
results.push(self.delete_schedule("", Some(pause)).await?);
}
Ok(results)
}
pub async fn enable_bedtime(
&self,
network_id: &str,
profile_id: &str,
start_time: &str,
end_time: &str,
days: Option<&[&str]>,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
let days = days.unwrap_or(ALL_DAYS);
self.create_schedule(
network_id, profile_id, "Bedtime", days, start_time, end_time, true, parent,
)
.await
}
pub async fn set_weekday_bedtime(
&self,
network_id: &str,
profile_id: &str,
start_time: &str,
end_time: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.enable_bedtime(
network_id,
profile_id,
start_time,
end_time,
Some(WEEKDAYS),
parent,
)
.await
}
pub async fn set_weekend_bedtime(
&self,
network_id: &str,
profile_id: &str,
start_time: &str,
end_time: &str,
parent: Option<&Value>,
) -> Result<Envelope, Error> {
self.enable_bedtime(
network_id,
profile_id,
start_time,
end_time,
Some(WEEKEND),
parent,
)
.await
}
}
fn is_path_or_url(reference: &str) -> bool {
let lower = reference.to_lowercase();
reference.starts_with('/') || lower.starts_with("http://") || lower.starts_with("https://")
}