1use std::cmp::Ordering;
4use std::collections::BTreeSet;
5
6use nibkeep_base::{EntityId, SpaceId};
7use nibkeep_model::storage::Statements;
8use nibkeep_model::{Decimal, FieldName, Languages, State, TypeName, Types, Value};
9use nibkeep_time::{Day, Start};
10
11use super::Library;
12use super::entities::{
13 Listed, PART, display_name, kept_apart, listed_from, name_on, things, with_type,
14};
15use super::links::may_link;
16use crate::NodeError;
17
18#[derive(Clone, Debug, Default, PartialEq, Eq)]
21pub struct Listing {
22 pub of_type: Option<TypeName>,
24 pub conditions: Vec<(FieldName, Value)>,
27 pub order_by: Option<FieldName>,
32 pub on: Option<Day>,
35}
36
37impl Library {
38 pub fn list_members(
47 &self,
48 space: SpaceId,
49 list: EntityId,
50 ) -> Result<Vec<nibkeep_log::list::Member>, NodeError> {
51 let open = self.space(space)?;
52 let state = open.stored.log().state();
53 Ok(nibkeep_log::list::members(state, state.canonical(list)?)?)
54 }
55
56 pub fn list(
64 &self,
65 space: SpaceId,
66 listing: &Listing,
67 today: Day,
68 ) -> Result<Vec<Listed>, NodeError> {
69 let open = self.space(space)?;
70 let state = open.stored.log().state();
71 let known = (&open.types, &self.languages);
72 let day = listing.on.unwrap_or(today);
73 let mut listed = if listing.conditions.is_empty() {
74 self.entities(space, listing.of_type.as_ref())?
75 } else {
76 open.stored.reading(|stored| {
77 let mut candidates: Option<BTreeSet<EntityId>> = None;
81 for (field, value) in &listing.conditions {
82 if matches!(
83 value,
84 Value::Name(_) | Value::Decimal(_) | Value::Quantity(_)
85 ) {
86 continue;
87 }
88 let mut found = BTreeSet::new();
89 for target in targets(state, value)? {
90 found.extend(stored.find(field, &target)?);
91 }
92 candidates = Some(match candidates {
93 None => found,
94 Some(before) => before.intersection(&found).copied().collect(),
95 });
96 }
97 let candidates = match (candidates, &listing.of_type) {
98 (Some(candidates), _) => candidates,
99 (None, Some(of_type)) => with_type(stored, of_type)?,
100 (None, None) => things(state)?,
101 };
102 let mut kept = BTreeSet::new();
103 for entity in candidates {
104 let entity = state.canonical(entity)?;
105 if kept.contains(&entity)
106 || state.is_deleted(entity)?
107 || kept_apart(state, entity)?
108 {
109 continue;
110 }
111 if let Some(of_type) = &listing.of_type
112 && !state.types(entity)?.contains(of_type)
113 {
114 continue;
115 }
116 let mut holds = true;
117 for (field, value) in &listing.conditions {
118 if !shows(state, known, (entity, day), field, value)? {
119 holds = false;
120 break;
121 }
122 }
123 if holds {
124 kept.insert(entity);
125 }
126 }
127 listed_from(state, known.0, known.1, (kept, PART))
128 })?
129 };
130 if listing.on.is_some() {
132 open.stored.reading(|_| {
133 for entity in &mut listed {
134 entity.name = name_on(state, known.0, known.1, entity.id, day)?;
135 }
136 Ok::<_, NodeError>(())
137 })?;
138 listed.sort_by_cached_key(|entity| {
139 let name = entity.name.as_deref().map(str::to_lowercase);
140 (name.is_none(), name, entity.id)
141 });
142 }
143 let Some(field) = &listing.order_by else {
144 return Ok(listed);
145 };
146 open.stored.reading(|_| {
147 let mut keyed = Vec::with_capacity(listed.len());
148 for entity in listed {
149 let key = sort_key(state, known, (entity.id, day), field)?;
150 keyed.push((key, entity));
151 }
152 keyed.sort_by(|(left, _), (right, _)| match (left, right) {
154 (Some(left), Some(right)) => left.cmp(right),
155 (Some(_), None) => Ordering::Less,
156 (None, Some(_)) => Ordering::Greater,
157 (None, None) => Ordering::Equal,
158 });
159 Ok(keyed.into_iter().map(|(_, entity)| entity).collect())
160 })
161 }
162}
163
164impl Library {
165 pub fn types_with(
172 &self,
173 space: SpaceId,
174 of_type: &TypeName,
175 ) -> Result<BTreeSet<TypeName>, NodeError> {
176 let open = self.space(space)?;
177 let state = open.stored.log().state();
178 open.stored.reading(|stored| {
179 let mut held = BTreeSet::from([of_type.clone()]);
180 for entity in with_type(stored, of_type)? {
181 held.extend(state.types(entity)?);
182 }
183 Ok(held)
184 })
185 }
186}
187
188fn targets<S: Statements>(state: &State<S>, value: &Value) -> Result<Vec<Value>, NodeError>
191where
192 NodeError: From<S::Error>,
193{
194 let Some(entity) = value.as_reference() else {
195 return Ok(vec![value.clone()]);
196 };
197 let canonical = state.canonical(entity)?;
198 let mut targets = vec![Value::Reference(canonical)];
199 for member in state.merged(canonical)? {
200 if member != canonical {
201 targets.push(Value::Reference(member));
202 }
203 }
204 if !targets.contains(value) {
205 targets.push(value.clone());
206 }
207 Ok(targets)
208}
209
210fn shown<S: Statements>(
213 state: &State<S>,
214 (types, languages): (&Types, &Languages),
215 (entity, day): (EntityId, Day),
216 field: &FieldName,
217) -> Result<Vec<Value>, NodeError>
218where
219 NodeError: From<S::Error>,
220{
221 let definition = types.field(field);
222 let (shown, _) = state.resolve_counted(entity, field, definition.as_ref(), day, languages)?;
223 Ok(shown
224 .into_iter()
225 .map(|(statement, _)| statement.value.clone())
226 .collect())
227}
228
229fn shows<S: Statements>(
233 state: &State<S>,
234 known: (&Types, &Languages),
235 at: (EntityId, Day),
236 field: &FieldName,
237 value: &Value,
238) -> Result<bool, NodeError>
239where
240 NodeError: From<S::Error>,
241{
242 let (entity, _) = at;
243 for shown in shown(state, known, at, field)? {
244 let same = match (&shown, value) {
245 (Value::Reference(shown), Value::Reference(wanted)) => {
246 let wanted = state.canonical(*wanted)?;
249 state.canonical(*shown)? == wanted && may_link(state, entity, wanted)?
250 }
251 (Value::Name(shown), Value::Name(wanted)) => shown.full() == wanted.full(),
252 (Value::Quantity(shown), Value::Quantity(wanted)) => {
253 shown.unit() == wanted.unit() && size(shown.number()) == size(wanted.number())
254 }
255 (shown, wanted) => match (number(shown), number(wanted)) {
256 (Some(shown), Some(wanted)) => shown == wanted,
257 _ => shown == wanted,
258 },
259 };
260 if same {
261 return Ok(true);
262 }
263 }
264 Ok(false)
265}
266
267fn number(value: &Value) -> Option<(i128, i64)> {
270 match value {
271 Value::Integer(integer) => Some(size(
272 Decimal::new(i128::from(*integer), 0).expect("an integer is a decimal"),
273 )),
274 Value::Decimal(decimal) => Some(size(*decimal)),
275 _ => None,
276 }
277}
278
279fn size(decimal: Decimal) -> (i128, i64) {
281 let (mut mantissa, mut exponent) = (decimal.mantissa(), decimal.exponent());
282 if mantissa == 0 {
283 return (0, 0);
284 }
285 while mantissa % 10 == 0 {
286 mantissa /= 10;
287 exponent += 1;
288 }
289 (mantissa, exponent)
290}
291
292#[derive(Clone, Debug, PartialEq)]
294enum SortKey {
295 Boolean(bool),
297 Number(f64),
299 Measure(bool, String, f64),
302 Date(Option<(Day, u32)>),
305 Text(String),
307}
308
309impl SortKey {
310 fn rank(&self) -> u8 {
312 match self {
313 Self::Boolean(_) => 0,
314 Self::Number(_) => 1,
315 Self::Measure(..) => 2,
316 Self::Date(..) => 3,
317 Self::Text(_) => 4,
318 }
319 }
320
321 fn cmp(&self, other: &Self) -> Ordering {
322 match (self, other) {
323 (Self::Boolean(left), Self::Boolean(right)) => left.cmp(right),
324 (Self::Number(left), Self::Number(right)) => left.total_cmp(right),
325 (Self::Measure(other, unit, left), Self::Measure(other_right, unit_right, right)) => {
326 (other, unit)
327 .cmp(&(other_right, unit_right))
328 .then_with(|| left.total_cmp(right))
329 }
330 (Self::Date(left), Self::Date(right)) => left.cmp(right),
331 (Self::Text(left), Self::Text(right)) => left.cmp(right),
332 _ => self.rank().cmp(&other.rank()),
333 }
334 }
335}
336
337fn sort_key<S: Statements>(
340 state: &State<S>,
341 known: (&Types, &Languages),
342 at: (EntityId, Day),
343 field: &FieldName,
344) -> Result<Option<SortKey>, NodeError>
345where
346 NodeError: From<S::Error>,
347{
348 let Some(value) = shown(state, known, at, field)?.into_iter().next() else {
349 return Ok(None);
350 };
351 let decimal = |mantissa: i128, exponent: i64| {
352 #[expect(clippy::cast_precision_loss, reason = "close enough to order by")]
353 let mantissa = mantissa as f64;
354 mantissa * 10_f64.powi(i32::try_from(exponent).unwrap_or(0))
355 };
356 Ok(match value {
357 Value::Boolean(boolean) => Some(SortKey::Boolean(boolean)),
358 #[expect(clippy::cast_precision_loss, reason = "close enough to order by")]
359 Value::Integer(integer) => Some(SortKey::Number(integer as f64)),
360 Value::Decimal(number) => Some(SortKey::Number(decimal(
361 number.mantissa(),
362 number.exponent(),
363 ))),
364 Value::Quantity(quantity) => {
365 let number = quantity.number();
366 let (types, _) = known;
367 let unit = types
368 .field(field)
369 .and_then(|definition| definition.unit().map(str::to_owned));
370 Some(SortKey::Measure(
371 unit.as_deref() != Some(quantity.unit()),
372 quantity.unit().to_owned(),
373 decimal(number.mantissa(), number.exponent()),
374 ))
375 }
376 Value::Date(date) => Some(match date.start() {
377 Start::BeginningOfTime => SortKey::Date(None),
378 Start::At { day, second } => SortKey::Date(Some((day, second.unwrap_or(0)))),
379 }),
380 Value::Text(text) => Some(SortKey::Text(text.to_lowercase())),
381 Value::Name(name) => Some(SortKey::Text(name.full().to_lowercase())),
382 Value::Reference(entity) => {
383 let (types, languages) = known;
384 display_name(state, types, languages, state.canonical(entity)?)?
385 .map(|name| SortKey::Text(name.to_lowercase()))
386 }
387 Value::Blob(_) | Value::Unknown(_) => None,
388 })
389}