use crate::dynamic_data::script_handling::script::Script; use crate::PkmnResult; use indexmap::IndexMap; use std::sync::Arc; #[derive(Debug, Default)] pub struct ScriptSet { scripts: IndexMap>>, } impl ScriptSet { pub fn add(&mut self, script: Box) -> Arc> { if let Some(existing) = self.scripts.get(script.name()) { existing.stack(); return existing.clone(); } let arc = Arc::new(script); self.scripts.insert(arc.name().to_string(), arc.clone()); self.scripts.last().unwrap().1.clone() } pub fn stack_or_add<'b, F>( &mut self, key: &str, instantiation: &'b F, ) -> PkmnResult>> where F: Fn() -> PkmnResult>, { if let Some(existing) = self.scripts.get(key) { existing.stack(); return Ok(existing.clone()); } let script = instantiation()?; let arc = Arc::new(script); self.scripts.insert(arc.name().to_string(), arc.clone()); Ok(self.scripts.last().unwrap().1.clone()) } pub fn get(&self, key: &str) -> Option<&Arc>> { self.scripts.get(key) } pub fn remove(&mut self, key: &str) { let value = self.scripts.shift_remove(key); if let Some(script) = value { script.on_remove(); } } pub fn clear(&mut self) { for script in &self.scripts { script.1.on_remove(); } self.scripts.clear(); } pub fn has(&self, key: &str) -> bool { self.scripts.contains_key(key) } pub fn at(&self, index: usize) -> &Arc> { &self.scripts[index] } pub fn count(&self) -> usize { self.scripts.len() } }