use crate::model::{Boundary, HashMap, With};
use log::warn;
use std::sync::{Arc, Mutex};
const MISSING_FUNCTION: &str = "Missing function. Please register";
pub type Data<T> = Arc<Mutex<T>>;
pub type TaskResult = Option<Boundary>;
type TaskCallback<T> = Box<dyn Fn(Data<T>) -> TaskResult + Sync>;
type GatewayCallback<T> = Box<dyn Fn(Data<T>) -> With + Sync>;
pub struct Eventhandler<T> {
task_func: HashMap<String, TaskCallback<T>>,
gateway_func: HashMap<String, GatewayCallback<T>>,
}
impl<T> Default for Eventhandler<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Eventhandler<T> {
pub fn new() -> Self {
Self {
task_func: Default::default(),
gateway_func: Default::default(),
}
}
pub fn add_task<F>(&mut self, name: impl Into<String>, func: F)
where
F: Fn(Data<T>) -> TaskResult + 'static + Sync,
{
self.task_func.insert(name.into(), Box::new(func));
}
pub(crate) fn run_task(&self, key: &str, data: Data<T>) -> TaskResult {
if let Some(func) = self.task_func.get(key) {
return (*func)(data);
} else {
warn!("{}: {}", MISSING_FUNCTION, key);
}
None
}
pub fn add_gateway<F>(&mut self, name: impl Into<String>, func: F)
where
F: Fn(Data<T>) -> With + 'static + Sync,
{
self.gateway_func.insert(name.into(), Box::new(func));
}
pub(crate) fn run_gateway(&self, key: &str, data: Data<T>) -> With {
if let Some(func) = self.gateway_func.get(key) {
return (*func)(data);
}
warn!("{}: {}", MISSING_FUNCTION, key);
With::Default
}
}