1use std::collections::HashMap;
2use std::pin::Pin;
3use std::future::Future;
4use crate::client::{ SlackEnvelope };
5
6pub type Predicate = fn(&SlackEnvelope) -> bool;
8
9pub type Callback = Box<dyn Fn(&SlackEnvelope) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
11
12
13pub struct EventHandler {
15 callbacks: Vec<(Predicate, Callback)>
16}
17
18impl EventHandler {
19 pub fn new() -> Self {
20 Self {
21 callbacks: Vec::new()
22 }
23 }
24
25 pub fn register_callback<F, Fut>(&mut self, predicate: Predicate, callback: F)
26 where
27 F: Fn(&SlackEnvelope) -> Fut + Send + Sync + 'static,
28 Fut: Future<Output=()> + Send + 'static
29 {
30 let async_callback: Callback = Box::new(
31 move |envelope: &SlackEnvelope| {
32 let fut = callback(envelope);
33 Box::pin(fut) as Pin<Box<dyn Future<Output=()> + Send>>
34 });
35 self.callbacks.push((predicate, async_callback));
36 }
37
38 pub async fn handle_event(&self, envelope: &SlackEnvelope) {
39 for (predicate, callback) in &self.callbacks {
40 if predicate(envelope) {
41 callback(envelope).await;
42 }
43 }
44 }
45}