use std::collections::HashSet;
use std::future::Future;
use laravel::db;
use laravel::model::__query;
use serde::Serialize;
use crate::node::NestedSet;
use crate::tree::{IntoTree, TreeNode};
const CHUNK: usize = 200;
#[derive(Debug, Clone, Serialize)]
pub struct WithAncestors<M> {
#[serde(flatten)]
pub node: M,
pub ancestors: Vec<M>,
}
pub trait LoadRelatives<M> {
fn with_ancestors(self) -> impl Future<Output = laravel::Result<Vec<WithAncestors<M>>>> + Send;
fn with_descendants(self) -> impl Future<Output = laravel::Result<Vec<TreeNode<M>>>> + Send;
}
impl<M: NestedSet> LoadRelatives<M> for Vec<M> {
async fn with_ancestors(self) -> laravel::Result<Vec<WithAncestors<M>>> {
let found = load(&self, M::where_ancestor_of).await?;
Ok(self
.into_iter()
.map(|node| {
let ancestors = found
.iter()
.filter(|&candidate| same_tree(candidate, &node) && node.is_descendant_of(candidate))
.cloned()
.collect();
WithAncestors { node, ancestors }
})
.collect())
}
async fn with_descendants(self) -> laravel::Result<Vec<TreeNode<M>>> {
let found = load(&self, M::where_descendant_of).await?;
Ok(self
.into_iter()
.map(|node| {
let below = found
.iter()
.filter(|&candidate| same_tree(candidate, &node) && candidate.is_descendant_of(&node));
let subtree: Vec<M> = std::iter::once(node.clone()).chain(below.cloned()).collect();
subtree
.into_tree()
.into_iter()
.next()
.expect("the node tops its own subtree")
})
.collect())
}
}
async fn load<M: NestedSet>(nodes: &[M], relation: fn(&M) -> db::Condition) -> laravel::Result<Vec<M>> {
let mut found = Vec::new();
for chunk in nodes.chunks(CHUNK) {
let rows = __query::<M>()
.filter(db::any(chunk.iter().map(relation)))
.order_by(M::lft_column().asc())
.get()
.await?;
found.extend(rows);
}
let mut seen = HashSet::new();
found.retain(|node| seen.insert(node.node_key().clone()));
found.sort_by_key(NestedSet::lft);
Ok(found)
}
fn same_tree<M: NestedSet>(a: &M, b: &M) -> bool {
a.scope().lock_name() == b.scope().lock_name()
}