use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use std::time::{Duration, SystemTime};
use super::super::staging;
use crate::conversation::Error;
use crate::conversation::rows::CONVERSATIONS;
use crate::conversation::search::visit_ids;
use crate::store::FileStore;
const UNSETTLED: Duration = Duration::from_secs(2);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Places {
pub stored: bool,
pub staged: bool,
}
#[derive(Default)]
struct Names {
names: Vec<String>,
read_at: Option<SystemTime>,
settled: bool,
}
impl Names {
fn stale(&self, now: Option<SystemTime>) -> bool {
now != self.read_at || !self.settled
}
}
#[derive(Default)]
pub struct Listing {
stored: Names,
staged: Names,
}
impl Listing {
pub fn names(&self) -> Vec<String> {
let all = self.stored.names.iter().chain(&self.staged.names);
all.cloned().collect::<BTreeSet<_>>().into_iter().collect()
}
pub fn places(&self, id: &str) -> Places {
let listed = |side: &Names| side.names.binary_search_by(|name| name.as_str().cmp(id));
Places {
stored: listed(&self.stored).is_ok(),
staged: listed(&self.staged).is_ok(),
}
}
}
fn stamp(directory: &Path) -> (Option<SystemTime>, bool) {
let at = fs::metadata(directory)
.and_then(|meta| meta.modified())
.ok();
let settled = at.is_none_or(|at| at.elapsed().is_ok_and(|age| age >= UNSETTLED));
(at, settled)
}
impl FileStore {
pub fn record_places(&self) -> Result<Listing, Error> {
let _held = self.lock()?;
let mut listing = Listing::default();
self.read_places(&mut listing, true)?;
Ok(listing)
}
pub(super) fn places_now(&self, id: &str, listing: &mut Listing) -> Result<Places, Error> {
self.read_places(listing, false)?;
Ok(listing.places(id))
}
pub(super) fn staged_exactly(&self, id: &str) -> Result<bool, Error> {
let restores = self.contained(self.root.join(staging::RESTORES), "restores")?;
let mut found = false;
visit_ids(&restores, |name| {
found |= name == id;
Ok(())
})?;
Ok(found)
}
fn read_places(&self, listing: &mut Listing, all: bool) -> Result<(), Error> {
let (read_at, settled) = stamp(&self.root.join(CONVERSATIONS));
if all || listing.stored.stale(read_at) {
let names = self.stored_names()?;
listing.stored = Names {
names,
read_at,
settled,
};
}
let restores = self.contained(self.root.join(staging::RESTORES), "restores")?;
let (read_at, settled) = stamp(&restores);
if all || listing.staged.stale(read_at) {
let mut names = Vec::new();
visit_ids(&restores, |id| {
names.push(id.to_string());
Ok(())
})?;
names.sort();
listing.staged = Names {
names,
read_at,
settled,
};
}
Ok(())
}
}