use std::sync::Arc;
use crate::{
ClientKind, ClientRef, ReportClient,
error::{Error, Result},
};
use openleadr_wire::{Event, Report, event::EventRequest, report::ReportRequest};
#[derive(Debug, Clone)]
pub struct EventClient<K> {
client: Arc<ClientRef<K>>,
data: Event,
}
impl<K: ClientKind> EventClient<K> {
pub(super) fn from_event(client: Arc<ClientRef<K>>, event: Event) -> Self {
Self {
client,
data: event,
}
}
pub fn id(&self) -> &openleadr_wire::event::EventId {
&self.data.id
}
pub fn created_date_time(&self) -> chrono::DateTime<chrono::Utc> {
self.data.created_date_time
}
pub fn modification_date_time(&self) -> chrono::DateTime<chrono::Utc> {
self.data.modification_date_time
}
pub fn content(&self) -> &EventRequest {
&self.data.content
}
pub fn content_mut(&mut self) -> &mut EventRequest {
&mut self.data.content
}
pub async fn update(&mut self) -> Result<()> {
self.data = self
.client
.put(&format!("events/{}", self.id()), &self.data.content)
.await?;
Ok(())
}
pub async fn delete(self) -> Result<Event> {
self.client.delete(&format!("events/{}", self.id())).await
}
pub fn new_report(&self, client_name: String) -> ReportRequest {
ReportRequest {
event_id: self.id().clone(),
client_name,
report_name: None,
payload_descriptors: None,
resources: vec![],
}
}
pub async fn create_report(&self, report_data: ReportRequest) -> Result<ReportClient<K>> {
if &report_data.event_id != self.id() {
return Err(Error::InvalidParentObject);
}
let report = self.client.post("reports", &report_data).await?;
Ok(ReportClient::from_report(self.client.clone(), report))
}
async fn get_reports_req(
&self,
client_name: Option<&str>,
skip: usize,
limit: usize,
) -> Result<Vec<ReportClient<K>>> {
let skip_str = skip.to_string();
let limit_str = limit.to_string();
let mut query = vec![
("programID", self.content().program_id.as_str()),
("eventID", self.id().as_str()),
("skip", &skip_str),
("limit", &limit_str),
];
if let Some(client_name) = client_name {
query.push(("clientName", client_name));
}
let reports: Vec<Report> = self.client.get("reports", &query).await?;
Ok(reports
.into_iter()
.map(|report| ReportClient::from_report(self.client.clone(), report))
.collect())
}
pub async fn get_report_list(&self, client_name: Option<&str>) -> Result<Vec<ReportClient<K>>> {
self.client
.iterate_pages(|skip, limit| self.get_reports_req(client_name, skip, limit))
.await
}
}