use std::sync::Arc;
use rho_sdk::tool::Tool;
use super::super::code_mode::{CodeModeSurface, ContextExposure, ScriptTool};
#[derive(Default)]
pub(super) struct ToolInventory {
tools: Vec<Arc<dyn Tool>>,
names: Vec<String>,
hidden: Vec<Arc<dyn Tool>>,
surface: Arc<CodeModeSurface>,
}
impl ToolInventory {
pub(super) fn tools(&self) -> &[Arc<dyn Tool>] {
&self.tools
}
pub(super) fn surface(&self) -> &Arc<CodeModeSurface> {
&self.surface
}
pub(super) fn named_tools(&self) -> impl Iterator<Item = (&str, &Arc<dyn Tool>)> {
self.names.iter().map(String::as_str).zip(&self.tools)
}
pub(super) fn extend(&mut self, tools: &[Arc<dyn Tool>], exposure: ContextExposure) {
match exposure {
ContextExposure::Direct => {}
ContextExposure::Hidden => self.hidden.extend(tools.iter().cloned()),
}
self.mutate(|all| all.extend(tools.iter().cloned()));
}
pub(super) fn remove(&mut self, tools: &[Arc<dyn Tool>]) {
let removed = |tool: &Arc<dyn Tool>| tools.iter().any(|gone| Arc::ptr_eq(gone, tool));
self.hidden.retain(|tool| !removed(tool));
self.mutate(|all| all.retain(|tool| !removed(tool)));
}
pub(super) fn mutate<T>(&mut self, mutation: impl FnOnce(&mut Vec<Arc<dyn Tool>>) -> T) -> T {
let result = mutation(&mut self.tools);
self.names = self.tools.iter().map(|tool| tool.spec().name).collect();
let hidden = &self.hidden;
self.surface
.sync_entries(self.named_tools().map(|(name, tool)| {
let exposure = if hidden.iter().any(|entry| Arc::ptr_eq(entry, tool)) {
ContextExposure::Hidden
} else {
ContextExposure::Direct
};
ScriptTool::new(name.to_owned(), tool.clone(), exposure)
}));
result
}
}