use crate::ecs::asset_id::MeshId;
use crate::ecs::generational_registry::GenerationalRegistry;
use crate::ecs::mesh::components::Mesh;

pub struct MeshCache {
    pub registry: GenerationalRegistry<Mesh>,
}

impl Default for MeshCache {
    fn default() -> Self {
        Self {
            registry: GenerationalRegistry::new(),
        }
    }
}

pub fn mesh_cache_insert(cache: &mut MeshCache, name: String, mesh: Mesh) -> MeshId {
    if let Some((index, generation)) = cache.registry.lookup_index(&name) {
        return MeshId { index, generation };
    }
    let (index, generation) = cache.registry.insert(name, mesh);
    cache.registry.add_reference(index);
    MeshId { index, generation }
}

pub fn mesh_cache_lookup_id(cache: &MeshCache, name: &str) -> Option<MeshId> {
    cache
        .registry
        .lookup_index(name)
        .map(|(index, generation)| MeshId { index, generation })
}

pub fn mesh_cache_remove(cache: &mut MeshCache, name: &str) -> Option<Mesh> {
    if let Some((index, generation)) = cache.registry.lookup_index(name) {
        cache.registry.remove(index, generation)
    } else {
        None
    }
}

pub fn mesh_cache_remove_by_id(cache: &mut MeshCache, id: MeshId) -> Option<Mesh> {
    cache.registry.remove(id.index, id.generation)
}

pub fn mesh_cache_iter(cache: &MeshCache) -> impl Iterator<Item = (&String, &Mesh)> {
    cache
        .registry
        .index_to_name
        .iter()
        .enumerate()
        .filter_map(|(index, name_opt)| {
            name_opt.as_ref().and_then(|name| {
                cache.registry.entries[index]
                    .as_ref()
                    .map(|mesh| (name, mesh))
            })
        })
}
