use tokio::sync::broadcast;

pub struct EventBus<T>
where
  T: Clone + std::fmt::Debug,
{
  sender: broadcast::Sender<T>,
  _receiver: broadcast::Receiver<T>,
}

impl<T: Clone + std::fmt::Debug> EventBus<T> {
  pub fn new() -> Self {
    let (sender, receiver) = broadcast::channel(1000);
    Self {
      sender,
      _receiver: receiver,
    }
  }

  pub fn publish(&self, event: T) {
    if let Err(e) = self.sender.send(event) {
      eprintln!("{e}")
    }
  }

  pub fn subscribe(&self) -> broadcast::Receiver<T> {
    self.sender.subscribe()
  }
}
