use std::collections::HashMap;
use std::sync::OnceLock;
use crate::format::error::LoadError;
use crate::format::manifest::ManifestPixelRef;
use crate::layer::{LayerId, LayerNode};
pub type IdMap = HashMap<u64, LayerId>;
pub struct SerializedEntity {
pub body: serde_json::Value,
pub pixel_blobs: Vec<PixelBlobSpec>,
}
pub struct PixelBlobSpec {
pub blob_key: String,
pub source_node_id: LayerId,
pub pixels: ManifestPixelRef,
}
pub struct LayerKindRegistration {
pub type_id: &'static str,
pub display_name: &'static str,
pub can_have_mask: bool,
pub can_rename: bool,
pub has_thumbnail: bool,
pub icon: &'static str,
pub serialize: fn(&LayerNode) -> SerializedEntity,
pub deserialize: fn(body: &serde_json::Value, id: LayerId) -> Result<LayerNode, LoadError>,
pub remap_ids: fn(&mut LayerNode, &IdMap),
}
pub struct LayerKindRegistry {
entries: Vec<LayerKindRegistration>,
by_type_id: HashMap<&'static str, usize>,
}
impl Default for LayerKindRegistry {
fn default() -> Self {
Self::new()
}
}
impl LayerKindRegistry {
pub fn new() -> Self {
let entries: Vec<LayerKindRegistration> = super::layer_kinds::registrations();
let mut by_type_id = HashMap::with_capacity(entries.len());
for (i, reg) in entries.iter().enumerate() {
by_type_id.insert(reg.type_id, i);
}
LayerKindRegistry {
entries,
by_type_id,
}
}
pub fn get(&'static self, type_id: &str) -> Option<&'static LayerKindRegistration> {
self.by_type_id.get(type_id).map(|&i| &self.entries[i])
}
pub fn all(&'static self) -> Vec<&'static LayerKindRegistration> {
let mut v: Vec<_> = self.entries.iter().collect();
v.sort_by_key(|reg| reg.type_id);
v
}
}
pub fn registry() -> &'static LayerKindRegistry {
static REGISTRY: OnceLock<LayerKindRegistry> = OnceLock::new();
REGISTRY.get_or_init(LayerKindRegistry::new)
}