use std::fmt::Debug;
use std::collections::HashSet;
use crate::event::*;
use crate::sender::*;
pub trait Handler: Sender + Send + Debug {
type Sig: IsSig<Sig = Self::Sig> + Debug;
fn get_handler_component_mut(&mut self) -> &mut HandlerComponent<Self::Sig>;
fn get_handler_component(&self) -> &HandlerComponent<Self::Sig>;
fn on_attach(&mut self) {}
fn on_detach(&mut self) {}
fn init(&mut self) {}
fn handle(&mut self, _event: &Self::Event) {}
fn get_init_subscriptions(&self) -> Vec<Self::Sig> {
Vec::new()
}
fn get_id(&self) -> Option<usize> {
self.get_handler_component().id
}
fn set_id(&mut self, id: usize) {
self.get_handler_component_mut().id = Some(id);
}
fn set_subscriptions(&mut self, subscriptions: Vec<Self::Sig>) {
for sig in subscriptions {
self.get_handler_component_mut().subscriptions.insert(sig);
}
}
fn attach(&self, sender: &mut dyn Sender<Event = Self::Event>) {
let id = self.get_id().expect(
"Event sender itself must be attached in order to attach event senders to it.");
sender.set_sender(self.get_sender().clone());
sender.set_associated_handler_id(id);
}
}
#[derive(Debug)]
pub struct HandlerComponent<S>
where
S: IsSig<Sig = S> {
id: Option<usize>,
subscriptions: HashSet<S>
}
impl<S> Default for HandlerComponent<S>
where
S: IsSig<Sig = S> {
fn default() -> Self {
Self {
id: None,
subscriptions: HashSet::new()
}
}
}
impl<S> Clone for HandlerComponent<S>
where
S: IsSig<Sig = S> {
fn clone(&self) -> Self {
Self {
id: None,
subscriptions: self.subscriptions.clone()
}
}
}