use_prelude!();
use std::sync::{Arc, Weak};

use crate::transport::{v2::V2Presence, v3::PresenceGraph};

/// A handle returned by [`ditto.presence().observe(...)`] for receiving presence updates.
///
/// Dropping this handle will cancel the observer.
///
/// ```
/// use dittolive_ditto::prelude::*;
/// # fn example(ditto: &Ditto) -> anyhow::Result<()> {
///
/// let _observer = ditto.presence().observe(|graph| {
///     println!("Latest presence graph: {graph:#?}");
/// });
///
/// // At this point, the observer callbacks will be canceled
/// drop(_observer);
/// # Ok(())
/// # }
/// ```
///
/// [`ditto.presence().observe(...)`]: crate::presence::Presence::observe
#[must_use = "Dropping a PresenceObserver will cancel its callback"]
pub struct PresenceObserver {
    _ctx: Arc<PresenceObserverCtx>,
}
pub(crate) type WeakPresenceObserver = Weak<PresenceObserverCtx>;

impl PresenceObserver {
    pub(crate) fn new(_ctx: Arc<PresenceObserverCtx>) -> Self {
        Self { _ctx }
    }
}

#[allow(deprecated)]
impl Observer for PresenceObserver {}

pub(crate) struct PresenceObserverCtx {
    pub(crate) on_presence: Box<dyn Fn(&PresenceGraph) + Send + Sync + 'static>,
}

impl PresenceObserverCtx {
    pub(crate) fn new(on_presence: Box<dyn Fn(&PresenceGraph) + Send + Sync + 'static>) -> Self {
        Self { on_presence }
    }
}

/// A token returned by `observe_peers`. Retain this object to continue
/// receiving callback updates.
#[doc(hidden)]
#[deprecated(note = "Use `ditto.presence().observe()` to get a `PresenceObserver` instead")]
pub struct PeersObserver {
    _context: Arc<PeersObserverCtx>,
}

#[allow(deprecated)]
impl PeersObserver {
    pub(crate) fn new(context: Arc<PeersObserverCtx>) -> Self {
        Self { _context: context }
    }
}

#[allow(deprecated)]
impl Observer for PeersObserver {}

pub(crate) struct PeersObserverCtx {
    pub(crate) on_presence: Box<dyn Fn(V2Presence) + Send + Sync + 'static>,
}

impl PeersObserverCtx {
    pub(crate) fn new(on_presence: Box<dyn Fn(V2Presence) + Send + Sync + 'static>) -> Self {
        Self { on_presence }
    }
}
