use nibkeep_base::{EntityId, SpaceId, StatementId};
use std::collections::BTreeMap;
use nibkeep_model::storage::Statements as _;
use nibkeep_model::{FieldName, Qualifiers, Value, fields};
use nibkeep_time::{Day, Edtf, Timestamp};
use super::entities::{EntityView, display_name, entity_view};
use super::links::{Links, links_to};
use super::{Author, Library};
use crate::NodeError;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct History {
pub id: EntityId,
pub name: Option<String>,
pub fields: Vec<FieldHistory>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FieldHistory {
pub field: FieldName,
pub values: Vec<PastValue>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PastValue {
pub statement: StatementId,
pub value: Value,
pub valid_time: Option<Edtf>,
pub language: Option<String>,
pub recorded: Timestamp,
pub restated: Option<Timestamp>,
pub replaced: Option<Timestamp>,
pub author: Option<Author>,
pub carried: Option<Carried>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Carried {
pub from: Option<SpaceId>,
pub from_name: Option<String>,
pub author: Option<Author>,
pub recorded: Option<u64>,
pub replaced: Option<u64>,
}
#[derive(Default)]
struct Noted {
authors: BTreeMap<String, Option<Author>>,
spaces: BTreeMap<SpaceId, Option<String>>,
}
impl Library {
pub fn history(
&self,
space: SpaceId,
entity: EntityId,
field: Option<&FieldName>,
) -> Result<Option<History>, NodeError> {
let open = self.space(space)?;
open.stored.reading(|stored| {
let log = stored.log();
let state = log.state();
let storage = state.storage();
let entity = state.canonical(entity)?;
if state.fields(entity)?.is_empty() && state.merged(entity)?.len() <= 1 {
let none = storage
.of_entity(entity)?
.iter()
.all(|(_, ids)| ids.is_empty());
if none {
return Ok(None);
}
}
let mut authors: BTreeMap<String, Option<Author>> = BTreeMap::new();
let mut noted = Noted::default();
let mut by_field: BTreeMap<FieldName, Vec<PastValue>> = BTreeMap::new();
for member in state.merged(entity)? {
for (name, ids) in storage.of_entity(member)? {
if field.is_some_and(|wanted| *wanted != name) {
continue;
}
for id in ids {
let Some(recorded) = storage.get(id)? else {
continue;
};
let author = match log.author_of(id)? {
Some(key) => {
let text = key.to_text();
if let Some(author) = authors.get(&text) {
author.clone()
} else {
let author = self.author_with_key(open, stored, &key)?;
authors.insert(text, author.clone());
author
}
}
None => None,
};
let statement = recorded.statement;
let carried =
self.carried(open, stored, &statement.qualifiers, &mut noted)?;
by_field.entry(name.clone()).or_default().push(PastValue {
statement: statement.id,
value: statement.value.clone(),
valid_time: statement.qualifiers.valid_time().cloned(),
language: statement.qualifiers.language().map(str::to_owned),
recorded: recorded.at,
restated: recorded.restated,
replaced: storage.superseded_at(id)?,
author,
carried,
});
}
}
}
let mut fields = Vec::new();
for (field, mut values) in by_field {
values.sort_by_key(|value| {
let noted = value.carried.as_ref().and_then(|carried| carried.recorded);
(
noted.unwrap_or_else(|| value.recorded.millis()),
value.recorded,
value.statement,
)
});
fields.push(FieldHistory { field, values });
}
Ok(Some(History {
id: entity,
name: display_name(state, &open.types, &self.languages, entity)?,
fields,
}))
})
}
fn carried(
&self,
open: &super::Space,
stored: &nibkeep_store::StoredLog,
qualifiers: &Qualifiers,
noted: &mut Noted,
) -> Result<Option<Carried>, NodeError> {
let millis = |field: &FieldName| match qualifiers.get(field) {
Some(Value::Integer(millis)) => u64::try_from(*millis).ok(),
_ => None,
};
let from = qualifiers
.get(&fields::CARRIED_FROM)
.and_then(Value::as_text)
.and_then(|text| text.parse::<SpaceId>().ok());
let key = qualifiers
.get(&fields::CARRIED_BY)
.and_then(Value::as_text)
.and_then(nibkeep_crypto::VerifyingKey::from_text);
let (recorded, replaced) = (
millis(&fields::CARRIED_AT),
millis(&fields::CARRIED_REPLACED),
);
if from.is_none() && key.is_none() && recorded.is_none() && replaced.is_none() {
return Ok(None);
}
let mut author = None;
if let Some(key) = &key {
let text = key.to_text();
if let Some(known) = noted.authors.get(&text) {
author.clone_from(known);
} else {
author = self.author_with_key(open, stored, key)?;
if author.is_none() {
let personal = self.space(self.info.personal)?;
author = self.author_with_key(personal, &personal.stored, key)?;
}
noted.authors.insert(text, author.clone());
}
}
let from_name = match from {
Some(space) if self.spaces.contains_key(&space) => {
if let Some(name) = noted.spaces.get(&space) {
name.clone()
} else {
let name = self.space_name(space)?;
noted.spaces.insert(space, name.clone());
name
}
}
_ => None,
};
Ok(Some(Carried {
from,
from_name,
author,
recorded,
replaced,
}))
}
pub fn name_as_of(
&self,
space: SpaceId,
entity: EntityId,
millis: u64,
) -> Result<Option<String>, NodeError> {
let open = self.space(space)?;
open.stored.reading(|stored| {
let state = stored.log().state_as_of(millis);
let entity = state.canonical(entity)?;
display_name(&state, &open.types, &self.languages, entity)
})
}
pub fn entity_as_of(
&self,
space: SpaceId,
entity: EntityId,
day: Day,
millis: u64,
) -> Result<Option<EntityView>, NodeError> {
let open = self.space(space)?;
open.stored.reading(|stored| {
let state = stored.log().state_as_of(millis);
entity_view(&state, &open.types, &self.languages, entity, day)
})
}
pub fn links_to_as_of(
&self,
space: SpaceId,
entity: EntityId,
day: Day,
millis: u64,
limit: usize,
) -> Result<Vec<Links>, NodeError> {
let open = self.space(space)?;
open.stored.reading(|stored| {
let state = stored.log().state_as_of(millis);
links_to(
&state,
&open.types,
&self.languages,
(entity, Some(day)),
(day, limit),
)
})
}
}