// r8r: rust port of n8n.io
// Initial author: Michael Cochran <mcochran@cochranblock.org>
// Built for: Tanner Woodrum, intended cofounder
// License: Unlicense (public domain dedication, see UNLICENSE)

use super::node::{Node, NodeFactory};
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};

pub struct Registry {
    nodes: HashMap<&'static str, Arc<dyn Node>>,
}

impl Registry {
    fn build() -> Self {
        let mut nodes = HashMap::new();
        for factory in inventory::iter::<NodeFactory> {
            nodes.insert(factory.name, (factory.make)());
        }
        Self { nodes }
    }

    pub fn global() -> &'static Registry {
        static R: OnceLock<Registry> = OnceLock::new();
        R.get_or_init(Self::build)
    }

    pub fn lookup(&self, name: &str) -> Option<Arc<dyn Node>> {
        self.nodes.get(name).cloned()
    }

    pub fn names(&self) -> Vec<&'static str> {
        let mut v: Vec<_> = self.nodes.keys().copied().collect();
        v.sort();
        v
    }

    pub fn count(&self) -> usize {
        self.nodes.len()
    }
}
