use brep_cam::library::interchange::{import_csv, import_fusion, ImportReport, LibraryDocument};
use brep_cam::library::{LibraryUnits, ToolLibrary};
use brep_cam::model::Tool;
use crate::store::ModelStore;
pub const CAM_TOOL_LIBRARY_KEY: &str = "@cam_tools";
pub fn load(store: &dyn ModelStore) -> Result<LibraryDocument, String> {
match store.read(CAM_TOOL_LIBRARY_KEY) {
None => Ok(LibraryDocument::new(ToolLibrary::new("User library"))),
Some(text) if text.trim().is_empty() => Ok(LibraryDocument::new(ToolLibrary::new("User library"))),
Some(text) => LibraryDocument::from_json(&text).map_err(|e| format!("the user tool library cannot be read: {e}")),
}
}
pub fn save(store: &dyn ModelStore, library: &LibraryDocument) -> Result<(), String> {
let text = library.to_json()?;
store.write(CAM_TOOL_LIBRARY_KEY, &text).map_err(|e| format!("the user tool library could not be saved: {e}"))
}
pub fn export_text(store: &dyn ModelStore) -> Result<String, String> {
load(store)?.to_json()
}
pub fn save_tool(store: &dyn ModelStore, tool: &Tool) -> Result<(), String> {
let mut library = load(store)?;
library.library.tools.retain(|t| t.id != tool.id);
library.library.insert(tool.clone()).map_err(|e| format!("user library: {e}"))?;
save(store, &library)
}
pub fn remove_tool(store: &dyn ModelStore, id: &str) -> Result<(), String> {
let mut library = load(store)?;
let before = library.library.tools.len();
library.library.tools.retain(|t| t.id.as_str() != id);
if library.library.tools.len() == before {
return Err(format!("no tool `{id}` in the user library"));
}
save(store, &library)
}
pub fn tool(store: &dyn ModelStore, id: &str) -> Result<Tool, String> {
load(store)?.library.tools.iter().find(|t| t.id.as_str() == id).cloned().ok_or_else(|| format!("no tool `{id}` in the user library"))
}
pub fn import_text(name: &str, text: &str) -> Result<ImportReport, String> {
let lower = name.to_ascii_lowercase();
if lower.ends_with(".csv") {
return import_csv(text, LibraryUnits::Millimeters);
}
if let Ok(document) = LibraryDocument::from_json(text) {
return Ok(ImportReport { document, issues: Vec::new() });
}
import_fusion(text)
}