use std::{
    hash::Hash,
    sync::{Arc, Weak, atomic::AtomicU32},
};

#[derive(Clone)]
pub struct WatchId {
    id: u32,
    count: Arc<()>,
}

#[derive(Clone)]
pub struct WeakWatchId {
    id: u32,
    count: Weak<()>,
}

impl PartialEq for WeakWatchId {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Eq for WeakWatchId {}

impl Hash for WeakWatchId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl WatchId {
    pub(super) fn new() -> Self {
        static GEN: AtomicU32 = AtomicU32::new(0);
        Self {
            id: GEN.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
            count: Arc::new(()),
        }
    }

    pub(super) fn weak(&self) -> WeakWatchId {
        WeakWatchId {
            id: self.id,
            count: Arc::downgrade(&self.count),
        }
    }
}

impl WeakWatchId {
    pub fn is_dead(&self) -> bool {
        self.count.upgrade().is_none()
    }
}

pub struct WatchState {
    /// if set, essentially always dirty
    pub special: bool,

    /// has the set of watched variables changed?
    pub dirty: bool,
}
