import { noop } from "@intelligentgraphics/ig.utilities";
import { CloseConnectionSymbol, } from "@intelligentgraphics/igd.core";
export const createConnectionManager = () => {
    const connections = new Map();
    const pendingInitializations = new Map();
    const createIdentifier = (type, id) => `${type}_${id}`;
    const getConnectionIds = (type) => Array.from(connections.keys())
        .filter(id => id.indexOf(type) === 0)
        .map(id => id.split(type + "_")[1]);
    const getConnection = (type, id) => connections.get(createIdentifier(type, id));
    const ensureConnection = (type, id, createConnection) => {
        const existingConnection = getConnection(type, id);
        if (existingConnection !== undefined) {
            return Promise.resolve(existingConnection);
        }
        const connectionIdentifier = createIdentifier(type, id);
        const pendingConnection = pendingInitializations.get(connectionIdentifier);
        if (pendingConnection !== undefined) {
            return pendingConnection;
        }
        const loadPromise = createConnection();
        pendingInitializations.set(connectionIdentifier, loadPromise);
        return loadPromise.then(connection => {
            connections.set(connectionIdentifier, connection);
            pendingInitializations.delete(connectionIdentifier);
            return connection;
        });
    };
    const registerConnection = (type, id, connection) => connections.set(createIdentifier(type, id), connection);
    const closeAllConnections = () => Promise.all(Array.from(connections.values()).map((connection) => {
        if (CloseConnectionSymbol in connection) {
            return connection[CloseConnectionSymbol]();
        }
    })).then(noop);
    return {
        ensureConnection,
        registerConnection,
        getConnectionIds,
        getConnection,
        closeAllConnections,
    };
};
