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