use std::collections::HashMap;
use super::{Change, Snapshot};
use crate::{
model::{EventData, FillPreview},
types::{FillId, Revision},
};
#[derive(Debug, Clone, Default)]
pub struct FillTracker {
fills: HashMap<FillId, (Revision, FillPreview)>,
synced: bool,
}
impl FillTracker {
pub fn apply(&mut self, change: &Change) {
match change {
Change::Resync(Snapshot::Private(snapshot)) => {
self.fills.clear();
for fill in &snapshot.fills {
self.update(fill.revision, fill.fill.clone());
}
self.synced = true;
}
Change::Resync(Snapshot::Public(_)) => {}
Change::Events(page) => {
for event in &page.events {
if let EventData::FillChanged(preview) = &event.data
&& self.is_newer(preview.id, event.revision)
{
self.update(event.revision, preview.clone());
}
}
}
}
}
pub fn is_synced(&self) -> bool {
self.synced
}
pub fn get(&self, id: FillId) -> Option<&FillPreview> {
self.fills.get(&id).map(|(_, preview)| preview)
}
pub fn iter(&self) -> impl Iterator<Item = &FillPreview> {
self.fills.values().map(|(_, preview)| preview)
}
fn is_newer(&self, id: FillId, revision: Revision) -> bool {
self.fills.get(&id).is_none_or(|(held, _)| revision > *held)
}
fn update(&mut self, revision: Revision, preview: FillPreview) {
if self.is_newer(preview.id, revision) {
self.fills.insert(preview.id, (revision, preview));
}
}
}
#[cfg(test)]
mod tests;