use crate::{Notification, Notify, NotifyError, NotifyReceipt};
use std::fmt;
use std::sync::{Arc, OnceLock};
pub const DEFAULT_PROVIDER_ID: &str = "default";
static NOTIFIER: OnceLock<Arc<dyn Notify>> = OnceLock::new();
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlreadyInitialized;
impl fmt::Display for AlreadyInitialized {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("notification implementation is already initialized")
}
}
impl std::error::Error for AlreadyInitialized {}
pub fn init(provider: Arc<dyn Notify>) -> Result<(), AlreadyInitialized> {
NOTIFIER.set(provider).map_err(|_| AlreadyInitialized)
}
pub fn get() -> Option<&'static Arc<dyn Notify>> {
NOTIFIER.get()
}
pub async fn notify(notification: &Notification) -> Result<Option<NotifyReceipt>, NotifyError> {
let Some(provider) = get() else {
return Ok(None);
};
provider.notify(notification).await.map(Some)
}