import BaseLogger from "./Logger";
const Logger = BaseLogger.createSubLogger("BackendManager");
export const createBackendManager = (initialBackends = {}) => {
    const backends = new Map();
    const backendCreators = new Map();
    const registerBackend = (type, creator) => backendCreators.set(type, creator);
    const loadBackend = (type) => {
        if (!backends.has(type)) {
            return loadBackends([type]).then(() => backends.get(type));
        }
        return Promise.resolve(backends.get(type));
    };
    const loadBackends = async (names) => {
        for (const entry of names) {
            if (backends.has(entry)) {
                continue;
            }
            const loader = backendCreators.get(entry);
            if (!loader) {
                throw new Error(`Unkown backend type: ${entry}`);
            }
            const result = await loader();
            backends.set(entry, result);
        }
    };
    const getBackendForServerType = (serverType) => {
        if (backends.has(serverType)) {
            return backends.get(serverType);
        }
    };
    for (const serverType in initialBackends) {
        const value = initialBackends[serverType];
        registerBackend(serverType, value);
    }
    return {
        registerBackend,
        loadBackend,
        getBackendForServerType,
    };
};
