import { UmbIconRegistry } from './icon.registry.js';
import { UMB_ICON_REGISTRY_CONTEXT } from './icon-registry.context-token.js';
import { UmbContextBase } from '../../../libs/class-api/index.js';
import { loadManifestPlainJs } from '../../../libs/extension-api/index.js';
import { UmbArrayState } from '../../../libs/observable-api/index.js';
import { umbExtensionsRegistry } from '../extension-registry/index.js';
export class UmbIconRegistryContext extends UmbContextBase {
    #registry;
    #manifestMap;
    #icons;
    constructor(host) {
        super(host, UMB_ICON_REGISTRY_CONTEXT);
        this.#manifestMap = new Map();
        this.#icons = new UmbArrayState([], (x) => x.name);
        this.icons = this.#icons.asObservable();
        this.approvedIcons = this.#icons.asObservablePart((icons) => icons.filter((x) => x.hidden !== true));
        this.#registry = new UmbIconRegistry();
        this.#registry.attach(host.getHostElement());
        this.observe(this.icons, (icons) => {
            //if (icons.length > 0) {
            this.#registry.setIcons(icons);
            //}
        });
        this.observe(umbExtensionsRegistry.byType('icons'), (manifests) => {
            manifests.forEach((manifest) => {
                if (this.#manifestMap.has(manifest.alias))
                    return;
                this.#manifestMap.set(manifest.alias, manifest);
                // TODO: Should we unInit a entry point if is removed?
                this.instantiateIcons(manifest);
            });
        });
    }
    async instantiateIcons(manifest) {
        if (manifest.js) {
            const js = await loadManifestPlainJs(manifest.js);
            if (!js || !js.default || !Array.isArray(js.default)) {
                throw new Error('Icon manifest JS-file must export an array of icons as the default export.');
            }
            this.#icons.append(js.default);
        }
    }
}
export { UmbIconRegistryContext as api };
