use std::collections::{HashMap, HashSet};
use crate::object::ObjectRef;
use crate::component::{Component, ComponentRef};
pub struct AttachmentsManager<T: Component>
{
map: HashMap<ObjectRef, HashSet<ComponentRef<T>>>,
inv_map: HashMap<ComponentRef<T>, ObjectRef>
}
impl<T: Component> AttachmentsManager<T>
{
pub fn new() -> AttachmentsManager<T>
{
return AttachmentsManager {
map: HashMap::new(),
inv_map: HashMap::new()
};
}
pub fn remove(&mut self, r: ComponentRef<T>)
{
if let Some(entity) = self.inv_map.get(&r) {
if let Some(set) = self.map.get_mut(entity) {
set.remove(&r);
self.inv_map.remove(&r);
}
}
}
pub fn attach(&mut self, entity: ObjectRef, r: ComponentRef<T>)
{
if let Some(set) = self.map.get_mut(&entity) {
set.insert(r);
} else {
let mut set = HashSet::new();
set.insert(r);
self.map.insert(entity, set);
}
self.inv_map.insert(r, entity);
}
pub fn list(&self, entity: ObjectRef) -> Option<Vec<ComponentRef<T>>>
{
if let Some(set) = self.map.get(&entity) {
let mut vec = Vec::with_capacity(set.len());
for v in set {
vec.push(*v);
}
return Some(vec);
}
return None;
}
pub fn clear(&mut self, entity: ObjectRef)
{
self.map.remove(&entity);
}
pub fn get_first(&self, entity: ObjectRef) -> Option<ComponentRef<T>>
{
if let Some(set) = self.map.get(&entity) {
Some(*set.iter().nth(0).unwrap())
} else {
None
}
}
}