use super::asset::{Asset, AssetTrait};
use crate::asset_id::AssetId;
use std::{collections::BTreeMap, fmt::Debug, sync::Arc};
use typemap::{Key, ShareCloneMap};
use uuid::Uuid;
#[derive(Debug, Clone, Default)]
pub struct Collection<T: AssetTrait>(BTreeMap<Uuid, Arc<Asset<T>>>);
impl<T: AssetTrait + 'static> Key for Collection<T> {
type Value = Collection<T>;
}
impl<T: AssetTrait> Collection<T> {
pub(crate) fn assets(&self) -> Vec<Arc<Asset<T>>> {
self.0.values().cloned().collect()
}
pub fn get(&self, id: &AssetId<T>) -> Option<&Arc<Asset<T>>> {
self.0.get(&id.id)
}
pub fn shared(&self) -> impl Iterator<Item = &Arc<Asset<T>>> {
self.0.values()
}
pub fn insert_shared(&mut self, asset: Arc<Asset<T>>) {
self.0.insert(asset.id.id, asset);
}
pub fn set_asset(&mut self, asset: Asset<T>) {
self.0.insert(asset.id.id, Arc::new(asset));
}
pub fn delete_asset(&mut self, id: AssetId<T>) {
self.0.remove(&id.id);
}
pub fn from_assets(assets: BTreeMap<Uuid, Arc<Asset<T>>>) -> Self {
Self(assets)
}
}
#[derive(Clone)]
pub struct Collections {
map: ShareCloneMap,
}
impl Default for Collections {
fn default() -> Self {
Self {
map: ShareCloneMap::custom(),
}
}
}
impl Debug for Collections {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Collections").finish_non_exhaustive()
}
}
impl Collections {
pub fn insert<T: AssetTrait>(&mut self, collection: Collection<T>) {
self.map.insert::<Collection<T>>(collection);
}
pub fn get<T: AssetTrait>(&self) -> Option<&Collection<T>> {
self.map.get::<Collection<T>>()
}
pub fn get_mut<T: AssetTrait>(&mut self) -> &mut Collection<T> {
self.map
.entry::<Collection<T>>()
.or_insert_with(Default::default)
}
}