80 lines
2.2 KiB
Rust
80 lines
2.2 KiB
Rust
use crate::dynamic_data::script_handling::script::{Script, ScriptContainer};
|
|
use crate::{PkmnResult, StringKey};
|
|
use indexmap::IndexMap;
|
|
|
|
#[derive(Debug, Default)]
|
|
pub struct ScriptSet {
|
|
scripts: IndexMap<StringKey, ScriptContainer>,
|
|
}
|
|
|
|
impl ScriptSet {
|
|
pub fn add(&mut self, script: Box<dyn Script>) -> ScriptContainer {
|
|
if let Some(lock) = self.scripts.get(script.name()) {
|
|
let mut existing = lock.get();
|
|
if let Some(v) = &mut *existing {
|
|
v.stack();
|
|
return lock.clone();
|
|
}
|
|
}
|
|
self.scripts
|
|
.insert(script.name().clone(), ScriptContainer::new(script));
|
|
self.scripts.last().unwrap().1.clone()
|
|
}
|
|
|
|
pub fn stack_or_add<'b, F>(
|
|
&mut self,
|
|
key: &StringKey,
|
|
instantiation: &'b F,
|
|
) -> PkmnResult<Option<ScriptContainer>>
|
|
where
|
|
F: Fn() -> PkmnResult<Option<Box<dyn Script>>>,
|
|
{
|
|
if let Some(lock) = self.scripts.get(key) {
|
|
let mut existing = lock.get();
|
|
if let Some(v) = &mut *existing {
|
|
v.stack();
|
|
return Ok(Some(lock.clone()));
|
|
}
|
|
}
|
|
let script = instantiation()?;
|
|
if let Some(script) = script {
|
|
let name = script.name().clone();
|
|
let arc = ScriptContainer::new(script);
|
|
self.scripts.insert(name, arc.clone());
|
|
Ok(Some(self.scripts.last().unwrap().1.clone()))
|
|
} else {
|
|
Ok(None)
|
|
}
|
|
}
|
|
|
|
pub fn get(&self, key: &StringKey) -> Option<&ScriptContainer> {
|
|
self.scripts.get(key)
|
|
}
|
|
|
|
pub fn remove(&mut self, key: &StringKey) {
|
|
let value = self.scripts.shift_remove(key);
|
|
if let Some(script) = value {
|
|
script.get().as_mut().unwrap().on_remove();
|
|
}
|
|
}
|
|
|
|
pub fn clear(&mut self) {
|
|
for script in &self.scripts {
|
|
script.1.get().as_mut().unwrap().on_remove();
|
|
}
|
|
self.scripts.clear();
|
|
}
|
|
|
|
pub fn has(&self, key: &StringKey) -> bool {
|
|
self.scripts.contains_key(key)
|
|
}
|
|
|
|
pub fn at(&self, index: usize) -> &ScriptContainer {
|
|
&self.scripts[index]
|
|
}
|
|
|
|
pub fn count(&self) -> usize {
|
|
self.scripts.len()
|
|
}
|
|
}
|