use crate::model::{Add, Instructions, Step, Torque};
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Level {
pub path: String,
pub name: String,
pub components: Vec<Component>,
pub mates: Vec<(String, String)>,
pub exploded_order: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Component {
pub path: String,
pub part: String,
pub part_id: Option<String>,
pub signature: String,
pub find_number: String,
pub grounded: bool,
pub fastener: bool,
pub serial_tracked: bool,
pub torque: Option<String>,
pub children: Option<Box<Level>>,
}
pub fn propose(block: &mut Instructions, root: &Level) {
block.steps.clear();
block.steps = level_steps(block, root);
}
pub fn level_steps(block: &mut Instructions, level: &Level) -> Vec<Step> {
let mut steps = Vec::new();
for group in order(level) {
let mut step = step_for(block, &group);
if let Some(children) = &group[0].children {
step.steps = level_steps(block, children);
}
steps.push(step);
}
steps
}
pub fn order(level: &Level) -> Vec<Vec<&Component>> {
let parts: Vec<&Component> = level.components.iter().filter(|c| !c.fastener).collect();
let mut placed: Vec<&Component> = Vec::new();
let mut placed_set: HashSet<&str> = HashSet::new();
let neighbours = adjacency(level);
let seed: HashMap<&str, usize> =
level.exploded_order.iter().rev().enumerate().map(|(i, p)| (p.as_str(), i)).collect();
for c in parts.iter().filter(|c| c.grounded) {
placed.push(c);
placed_set.insert(c.path.as_str());
}
if placed.is_empty() && seed.is_empty() {
if let Some(first) = parts.first() {
placed.push(first);
placed_set.insert(first.path.as_str());
}
}
while placed.len() < parts.len() {
let remaining = parts.iter().filter(|c| !placed_set.contains(c.path.as_str()));
let next = if !seed.is_empty() {
remaining
.clone()
.filter(|c| seed.contains_key(c.path.as_str()))
.min_by_key(|c| seed[c.path.as_str()])
.copied()
.or_else(|| mated_first(remaining.clone(), &neighbours, &placed_set))
} else {
mated_first(remaining.clone(), &neighbours, &placed_set)
};
let next = next.or_else(|| remaining.clone().next().copied()).expect("a remaining part");
placed.push(next);
placed_set.insert(next.path.as_str());
}
let mut groups: Vec<Vec<&Component>> = placed.into_iter().map(|c| vec![c]).collect();
let position: HashMap<&str, usize> = groups.iter().enumerate().map(|(i, g)| (g[0].path.as_str(), i)).collect();
let mut fastener_groups: Vec<(usize, usize, Vec<&Component>)> = Vec::new();
for (index, c) in level.components.iter().enumerate().filter(|(_, c)| c.fastener) {
let after = neighbours
.get(c.path.as_str())
.into_iter()
.flatten()
.filter_map(|n| position.get(n).copied())
.max()
.unwrap_or(usize::MAX);
match fastener_groups.iter_mut().find(|(_, _, g)| g[0].part == c.part) {
Some((rank, _, group)) => {
*rank = (*rank).max(after);
group.push(c);
}
None => fastener_groups.push((after, index, vec![c])),
}
}
fastener_groups.sort_by_key(|(rank, index, _)| (*rank, *index));
groups.extend(fastener_groups.into_iter().map(|(_, _, g)| g));
groups
}
fn mated_first<'a, 'b>(
mut remaining: impl Iterator<Item = &'b &'a Component>,
neighbours: &HashMap<&str, Vec<&str>>,
placed: &HashSet<&str>,
) -> Option<&'a Component>
where
'a: 'b,
{
remaining
.find(|c| neighbours.get(c.path.as_str()).is_some_and(|n| n.iter().any(|p| placed.contains(p))))
.copied()
}
fn adjacency(level: &Level) -> HashMap<&str, Vec<&str>> {
let mut map: HashMap<&str, Vec<&str>> = HashMap::new();
for (a, b) in &level.mates {
if a == b {
continue;
}
map.entry(a.as_str()).or_default().push(b.as_str());
map.entry(b.as_str()).or_default().push(a.as_str());
}
map
}
pub fn step_for(block: &mut Instructions, group: &[&Component]) -> Step {
let first = group[0];
let quantity = group.len();
let subassembly = first.children.is_some();
let title = match (subassembly, quantity) {
(true, _) => format!("Install sub-assembly {}", first.part),
(false, 1) => format!("Install {}", first.part),
(false, n) => format!("Install {n} × {}", first.part),
};
let torque = if first.fastener { first.torque.as_deref().and_then(Torque::from_attribute) } else { None };
Step {
id: block.next_id("MS"),
title,
adds: vec![Add {
find_number: first.find_number.clone(),
subassembly,
fastener: first.fastener,
serial_tracked: first.serial_tracked,
..Add::named(group.iter().map(|c| c.path.clone()).collect(), first.part_key(), &first.part)
}],
torque,
..Step::default()
}
}
impl Component {
pub fn part_key(&self) -> &str {
self.part_id.as_deref().unwrap_or(&self.part)
}
}
pub fn flatten(level: &Level) -> Vec<(&str, &Component)> {
let mut out = Vec::new();
fn walk<'a>(level: &'a Level, out: &mut Vec<(&'a str, &'a Component)>) {
for c in &level.components {
out.push((level.path.as_str(), c));
if let Some(children) = &c.children {
walk(children, out);
}
}
}
walk(level, &mut out);
out
}
pub fn find_level<'a>(root: &'a Level, path: &str) -> Option<&'a Level> {
if root.path == path {
return Some(root);
}
root.components.iter().filter_map(|c| c.children.as_deref()).find_map(|l| find_level(l, path))
}