use super::{delay_sender::DelaySender, event_handler::LoopEventHandler};
use crate::messaging::CanSend;
use std::fmt::Debug;
pub struct AdhocEvent<Data: 'static> {
pub description: String,
pub handler: Box<dyn FnOnce(&mut Data) + Send + 'static>,
}
impl<Data> Debug for AdhocEvent<Data> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.description)
}
}
pub trait AdhocEventSender<Data: 'static> {
fn send_adhoc_event(&self, description: &str, f: impl FnOnce(&mut Data) + Send + 'static);
fn schedule_adhoc_event(
&self,
description: &str,
f: impl FnOnce(&mut Data) + Send + 'static,
delay: time::Duration,
);
}
impl<Data: 'static, Event: From<AdhocEvent<Data>> + 'static> AdhocEventSender<Data>
for DelaySender<Event>
{
fn send_adhoc_event(&self, description: &str, f: impl FnOnce(&mut Data) + Send + 'static) {
self.send(AdhocEvent { description: description.to_string(), handler: Box::new(f) })
}
fn schedule_adhoc_event(
&self,
description: &str,
f: impl FnOnce(&mut Data) + Send + 'static,
delay: time::Duration,
) {
self.send_with_delay(
AdhocEvent { description: description.to_string(), handler: Box::new(f) }.into(),
delay,
)
}
}
pub fn handle_adhoc_events<Data: 'static>() -> LoopEventHandler<Data, AdhocEvent<Data>> {
LoopEventHandler::new_simple(|event: AdhocEvent<Data>, data| {
(event.handler)(data);
})
}