use std::collections::HashSet;
use super::{Doc, Map, ParseError, collect_child_ids};
pub(crate) fn patch_children(doc: &Doc, block: &mut Map, children: &[String]) -> Result<(), ParseError> {
let current = collect_child_ids(block);
if current == children {
return Ok(());
}
let Some(mut array) = block.get("sys:children").and_then(|value| value.to_array()) else {
return super::insert_children(doc, block, children);
};
let mut remaining: HashSet<_> = children.iter().collect();
let mut index = 0;
let mut old = 0;
for child in children {
while old < current.len() && current[old] != *child && !remaining.contains(¤t[old]) {
array.remove(index, 1)?;
old += 1;
}
if current.get(old) == Some(child) {
old += 1;
} else {
array.insert(index, child.clone())?;
}
remaining.remove(child);
index += 1;
}
if old < current.len() {
array.remove(index, (current.len() - old) as u64)?;
}
Ok(())
}