use std::collections::HashMap;
use laravel::model::{CreateBuilder, Model};
use serde::Serialize;
use crate::node::NestedSet;
#[derive(Debug, Clone, Serialize)]
pub struct TreeNode<M> {
#[serde(flatten)]
pub node: M,
pub depth: usize,
pub children: Vec<TreeNode<M>>,
}
pub trait IntoTree<M> {
fn into_tree(self) -> Vec<TreeNode<M>>;
fn into_flat_tree(self) -> Vec<M>;
fn into_flat_tree_with_depth(self) -> Vec<(M, usize)>;
}
impl<M: NestedSet> IntoTree<M> for Vec<M> {
fn into_tree(self) -> Vec<TreeNode<M>> {
let (mut slots, tops, children) = link(self);
tops.into_iter()
.map(|index| build(index, 0, &mut slots, &children))
.collect()
}
fn into_flat_tree(self) -> Vec<M> {
self.into_flat_tree_with_depth()
.into_iter()
.map(|(node, _)| node)
.collect()
}
fn into_flat_tree_with_depth(self) -> Vec<(M, usize)> {
let (mut slots, tops, children) = link(self);
let mut flat = Vec::with_capacity(slots.len());
let mut stack: Vec<(usize, usize)> = tops.into_iter().rev().map(|index| (index, 0)).collect();
while let Some((index, depth)) = stack.pop() {
if let Some(node) = slots[index].take() {
flat.push((node, depth));
}
if let Some(below) = children.get(&index) {
stack.extend(below.iter().rev().map(|&child| (child, depth + 1)));
}
}
flat
}
}
type Linked<M> = (Vec<Option<M>>, Vec<usize>, HashMap<usize, Vec<usize>>);
fn link<M: NestedSet>(nodes: Vec<M>) -> Linked<M> {
let positions: HashMap<&M::Key, usize> = nodes
.iter()
.enumerate()
.map(|(index, node)| (node.node_key(), index))
.collect();
let mut tops = Vec::new();
let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
for (index, node) in nodes.iter().enumerate() {
match node.parent_key().and_then(|parent| positions.get(parent)) {
Some(&parent) if parent != index => children.entry(parent).or_default().push(index),
_ => tops.push(index),
}
}
(nodes.into_iter().map(Some).collect(), tops, children)
}
fn build<M>(
index: usize,
depth: usize,
slots: &mut Vec<Option<M>>,
children: &HashMap<usize, Vec<usize>>,
) -> TreeNode<M> {
let node = slots[index].take().expect("each node is built once");
let children = children
.get(&index)
.map(|below| {
below
.iter()
.map(|&child| build(child, depth + 1, slots, children))
.collect()
})
.unwrap_or_default();
TreeNode { node, depth, children }
}
pub struct NewNode<M: Model> {
pub(crate) create: CreateBuilder<M>,
pub(crate) children: Vec<NewNode<M>>,
}
impl<M: Model> NewNode<M> {
pub fn new(create: impl Into<CreateBuilder<M>>) -> Self {
Self {
create: create.into(),
children: Vec::new(),
}
}
#[must_use]
pub fn children(mut self, children: impl IntoIterator<Item = NewNode<M>>) -> Self {
self.children.extend(children);
self
}
}