"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCatalogGroups = getCatalogGroups;
const util_1 = require("../util");
const Catalog_1 = require("./Catalog");
const getUserGroupsFromQuery_1 = require("./getUserGroupsFromQuery");
/**
 * Return an IGroupsByMembership object that contains all the groups, from all the
 * collections/scopes in the catalog, which the current user is an owner/member/admin of.
 * @param catalog
 * @param context
 * @returns
 */
function getCatalogGroups(catalog, context) {
    // create the response object
    const response = {
        owner: [],
        member: [],
        admin: [],
    };
    // create the catalog
    const instance = Catalog_1.Catalog.fromJson(catalog, context);
    const collectionUserGroups = instance.collectionNames.map((name) => {
        // important that we use .getCollection as that merges in the scope from the catalog
        const collection = instance.getCollection(name);
        return (0, getUserGroupsFromQuery_1.getUserGroupsFromQuery)(collection.scope, context.currentUser);
    });
    // get the scopes that do not have related collections
    const nakedScopeTargetEntities = Object.keys(catalog.scopes).reduce((acc, key) => {
        // check if there are colletions with this targetEntity
        const hasCollection = (catalog.collections || []).some((collection) => collection.targetEntity === key);
        // if not, add it to the list
        if (!hasCollection) {
            acc.push(key);
        }
        return acc;
    }, []);
    const scopeUserGroups = nakedScopeTargetEntities.map((targetEntity) => {
        const scopeQuery = instance.getScope(targetEntity);
        return (0, getUserGroupsFromQuery_1.getUserGroupsFromQuery)(scopeQuery, context.currentUser);
    });
    // Merge the naked scopes into the response
    [...scopeUserGroups, ...collectionUserGroups].forEach((groups) => {
        response.owner = [...response.owner, ...groups.owner];
        response.member = [...response.member, ...groups.member];
        response.admin = [...response.admin, ...groups.admin];
    });
    // ensure only unique entries in each array
    response.owner = response.owner.filter(util_1.unique);
    response.member = response.member.filter(util_1.unique);
    response.admin = response.admin.filter(util_1.unique);
    return response;
}
//# sourceMappingURL=getCatalogGroups.js.map