use std::collections::BTreeMap;
use std::sync::Arc;
use techy::core::node::NodeTree;
use techy::serialize::SerialValue;
use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
use crate::model::addr::NodeAddr;
use crate::model::aspects::PointId;
use crate::model::names::Name;
use crate::lang::Flm;
use super::many::format_many;
use super::joiner::{written_with_keys, CompiledWithinJoiner, JoinCx};
use super::style::{format, on_worker, Ancestor, CounterStyle, FormatError, FormatOptions, Parent};
use super::template::AncestorKeys;
use super::writer::NumberedValue;
use super::value::CounterValue;
pub const COUNTERS: TableName<Counters> = TableName::new("flm.counters");
#[derive(Clone, Debug)]
pub struct CounterRecord {
pub counter: Name,
pub value: CounterValue,
pub ancestors: Vec<Ancestor>,
pub style: Arc<CounterStyle>,
pub instance: Option<NodeAddr>,
}
impl CounterRecord {
pub fn is_nested(&self) -> bool {
is_nested(&self.counter, &self.ancestors)
}
}
pub(super) fn is_nested(counter: &Name, ancestors: &[Ancestor]) -> bool {
ancestors.last().is_some_and(|last| &last.counter == counter)
}
#[derive(Clone, Debug)]
pub struct NumberSegment {
content: Arc<NodeTree<Flm>>,
link: Option<PointId>,
}
impl NumberSegment {
pub fn new(content: Arc<NodeTree<Flm>>, link: Option<PointId>) -> NumberSegment {
NumberSegment { content, link }
}
pub fn content(&self) -> &Arc<NodeTree<Flm>> {
&self.content
}
pub fn link(&self) -> Option<PointId> {
self.link
}
}
#[derive(Clone, Debug, Default)]
pub struct ManyNumbers {
pub groups: Vec<Vec<NumberSegment>>,
pub unnumbered: Vec<PointId>,
}
#[derive(Debug, Default)]
pub struct Counters {
records: BTreeMap<PointId, Option<CounterRecord>>,
hierarchy: BTreeMap<Name, Arc<dyn CompiledWithinJoiner>>,
nesting: BTreeMap<Name, Arc<dyn CompiledWithinJoiner>>,
styles: Arc<BTreeMap<Name, Arc<CounterStyle>>>,
}
impl Counters {
pub fn insert(&mut self, point: PointId, record: Option<CounterRecord>) {
self.records.insert(point, record);
}
pub fn number_within(
&mut self,
counter: impl Into<Name>,
joiner: Arc<dyn CompiledWithinJoiner>,
) {
self.hierarchy.insert(counter.into(), joiner);
}
pub fn number_nested(
&mut self,
counter: impl Into<Name>,
joiner: Arc<dyn CompiledWithinJoiner>,
) {
self.nesting.insert(counter.into(), joiner);
}
pub(super) fn carry_styles(&mut self, styles: Arc<BTreeMap<Name, Arc<CounterStyle>>>) {
self.styles = styles;
}
pub fn style(&self, name: &Name) -> Option<&Arc<CounterStyle>> {
self.styles.get(name)
}
pub fn record(&self, point: PointId) -> Option<&CounterRecord> {
self.records.get(&point).and_then(Option::as_ref)
}
pub fn lookup(&self, point: PointId) -> Option<Option<&CounterRecord>> {
self.records.get(&point).map(Option::as_ref)
}
pub fn len(&self) -> usize {
self.records.len()
}
pub fn is_empty(&self) -> bool {
self.records.is_empty()
}
pub fn points(&self) -> impl Iterator<Item = (PointId, Option<&CounterRecord>)> + '_ {
self.records.iter().map(|(point, record)| (*point, record.as_ref()))
}
fn parent_of<'a>(&'a self, record: &'a CounterRecord) -> Option<Parent<'a>> {
let joiner = self.joiner_of(record)?;
Some(Parent::new(joiner.as_ref(), &record.ancestors))
}
fn joiner_of(&self, record: &CounterRecord) -> Option<&Arc<dyn CompiledWithinJoiner>> {
if record.is_nested() {
self.nesting.get(&record.counter)
} else {
self.hierarchy.get(&record.counter)
}
}
pub fn format(
&self,
point: PointId,
options: &FormatOptions,
) -> Option<Result<Vec<NumberSegment>, FormatError>> {
let record = self.record(point)?;
let parent = self.parent_of(record);
Some(
format(&record.value, &record.style, parent, options)
.map(|segments| link_all(segments, &[point])),
)
}
pub fn format_in_style(
&self,
point: PointId,
style: &CounterStyle,
options: &FormatOptions,
) -> Option<Result<Vec<NumberSegment>, FormatError>> {
let record = self.record(point)?;
let parent = self.parent_of(record);
Some(format(&record.value, style, parent, options).map(|segments| link_all(segments, &[point])))
}
pub(crate) fn format_with_keys(
&self,
point: PointId,
keys: AncestorKeys,
options: &FormatOptions,
) -> Option<Result<Vec<NumberSegment>, FormatError>> {
if keys == AncestorKeys::default() {
return self.format(point, options);
}
let record = self.record(point)?;
let mut own = Ancestor::new(
record.counter.clone(),
record.value.clone(),
Arc::clone(&record.style),
);
own.joiner = self.joiner_of(record).cloned();
own.instance = record.instance;
let mut chain = record.ancestors.clone();
chain.push(own);
let written = on_worker(|| {
let cx = JoinCx::new(&record.style);
written_with_keys(&chain, chain.len() - 1, keys, &cx)
});
Some(written.map(|part| vec![NumberSegment { content: part.content, link: Some(point) }]))
}
pub fn format_many(
&self,
points: &[PointId],
options: &FormatOptions,
) -> Result<ManyNumbers, FormatError> {
let mut unnumbered = Vec::new();
let mut groups: Vec<StyleGroup<'_>> = Vec::new();
for point in points {
let Some(record) = self.record(*point) else {
unnumbered.push(*point);
continue;
};
let style = match groups
.iter()
.position(|group| Arc::ptr_eq(group.style, &record.style))
{
Some(index) => index,
None => {
groups.push(StyleGroup {
style: &record.style,
values: Vec::new(),
points: Vec::new(),
});
groups.len() - 1
}
};
let mut value = NumberedValue::new(&record.value);
if let Some(parent) = self.parent_of(record) {
value = value.within(parent);
}
if let Some(instance) = record.instance {
value = value.in_instance(instance);
}
groups[style].values.push(value);
groups[style].points.push(*point);
}
let mut written = Vec::with_capacity(groups.len());
for group in &groups {
let segments = format_many(group.style, &group.values, options)?;
written.push(link_all(segments, &group.points));
}
Ok(ManyNumbers { groups: written, unnumbered })
}
}
struct StyleGroup<'a> {
style: &'a Arc<CounterStyle>,
values: Vec<NumberedValue<'a>>,
points: Vec<PointId>,
}
fn link_all(segments: Vec<super::Segment>, points: &[PointId]) -> Vec<NumberSegment> {
segments
.into_iter()
.map(|segment| {
let link = segment.link().and_then(|position| points.get(position).copied());
NumberSegment { content: Arc::clone(segment.content()), link }
})
.collect()
}
impl Table for Counters {
fn absorb(&mut self, piece: Counters) {
self.records.extend(piece.records);
self.hierarchy.extend(piece.hierarchy);
self.nesting.extend(piece.nesting);
if !piece.styles.is_empty() {
self.styles = piece.styles;
}
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
SerialValue::Map(
self.records
.iter()
.map(|(point, record)| {
let value = match record {
Some(record) => {
let mut entries = vec![
(
"counter".to_string(),
SerialValue::Str(record.counter.to_string()),
),
("value".to_string(), components(&record.value)),
(
"style".to_string(),
SerialValue::Str(record.style.name().to_string()),
),
];
push_instance(cx, &mut entries, record.instance);
let within = record
.ancestors
.iter()
.map(|ancestor| {
let mut entries = vec![
(
"counter".to_string(),
SerialValue::Str(ancestor.counter.to_string()),
),
("value".to_string(), components(&ancestor.value)),
];
push_instance(cx, &mut entries, ancestor.instance);
SerialValue::Map(entries)
})
.collect();
entries.push(("within".to_string(), SerialValue::List(within)));
SerialValue::Map(entries)
}
None => SerialValue::Null,
};
(point_key(cx, *point), value)
})
.collect(),
)
}
fn piece_class(&self) -> PieceClass {
if self.records.is_empty() && self.hierarchy.is_empty() && self.nesting.is_empty() {
PieceClass::Empty
} else {
PieceClass::DocumentFact
}
}
}
impl SingletonTable for Counters {
const NAME: &'static str = "flm.counters";
}
fn push_instance(
cx: &dyn ProjectCx,
entries: &mut Vec<(String, SerialValue)>,
instance: Option<NodeAddr>,
) {
if let Some(instance) = instance {
entries.push(("instance".to_string(), cx.node_ref(instance)));
}
}
fn components(value: &CounterValue) -> SerialValue {
SerialValue::List(value.components().iter().map(|part| SerialValue::Int(*part)).collect())
}
fn point_key(cx: &dyn ProjectCx, point: PointId) -> String {
format!("{}#{}", node_key(cx, point.addr), point.index)
}
fn node_key(cx: &dyn ProjectCx, addr: NodeAddr) -> String {
match cx.node_ref(addr) {
SerialValue::Str(text) => text,
other => format!("{other:?}"),
}
}