"use strict";
/* Copyright (c) 2018-2021 Environmental Systems Research Institute, Inc.
 * Apache-2.0 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getGroupThumbnailUrl = getGroupThumbnailUrl;
exports.getUserThumbnailUrl = getUserThumbnailUrl;
exports.migrateToCollectionKey = migrateToCollectionKey;
exports.getScopeGroupPredicate = getScopeGroupPredicate;
exports.getGroupPredicate = getGroupPredicate;
exports.getResultSiteRelativeLink = getResultSiteRelativeLink;
exports.addDefaultItemSearchPredicates = addDefaultItemSearchPredicates;
exports.getKilobyteSizeOfQuery = getKilobyteSizeOfQuery;
exports.expandPortalQuery = expandPortalQuery;
const internalContentUtils_1 = require("../content/_internal/internalContentUtils");
const util_1 = require("../util");
const isLegacySearchCategory_1 = require("./_internal/commonHelpers/isLegacySearchCategory");
const toCollectionKey_1 = require("./_internal/commonHelpers/toCollectionKey");
const applyWellKnownItemPredicates_1 = require("./_internal/applyWellKnownItemPredicates");
const expandPredicates_1 = require("./_internal/expandPredicates");
/**
 * Construct a the full url to a group thumbnail
 *
 * - If the group has a thumbnail, construct the full url
 * - If the group is not public, append on the token (if passed in)
 * @param portalUrl
 * @param group
 * @param token
 * @returns
 */
function getGroupThumbnailUrl(portalUrl, group, token) {
    let thumbnailUrl = null;
    if (group.thumbnail) {
        thumbnailUrl = `${portalUrl}/community/groups/${group.id}/info/${group.thumbnail}`;
        if (token && group.access !== "public") {
            thumbnailUrl = `${thumbnailUrl}?token=${token}`;
        }
    }
    return thumbnailUrl;
}
/**
 * Construct a the full url to a user thumbnail
 *
 * - If the user has a thumbnail, construct the full url
 * - If the user is not public, append on the token
 * @param portalUrl
 * @param user
 * @param token
 * @returns
 */
function getUserThumbnailUrl(portalUrl, user, token) {
    let thumbnailUrl = null;
    if (user.thumbnail) {
        thumbnailUrl = `${portalUrl}/community/users/${user.username}/info/${user.thumbnail}`;
        if (token && user.access !== "public") {
            thumbnailUrl = `${thumbnailUrl}?token=${token}`;
        }
    }
    return thumbnailUrl;
}
/**
 * Function that can migrate a legacy search category to a wellknown
 * collection key. Useful when the caller has an unknown value that
 * could either be a search category or wellknown collection.
 *
 * If the value passed is not a search category, it is returned as-is.
 *
 * @param collectionOrSearchCategory key to be migrated
 * @returns the migrated wellknown collection key
 */
function migrateToCollectionKey(collectionOrSearchCategory) {
    return (0, isLegacySearchCategory_1.isLegacySearchCategory)(collectionOrSearchCategory)
        ? (0, toCollectionKey_1.toCollectionKey)(collectionOrSearchCategory)
        : collectionOrSearchCategory;
}
/**
 * DEPRECATED: Please use `getGroupPredicate`
 * Searches through a catalog scope and retrieves the predicate responsible
 * for determining group sharing requirements.
 * Still in use in opendata-ui as of 03/26/2025
 * @param scope Catalog scope to search through
 * @returns The first predicate with a `group` field (if present)
 */
// istanbul ignore next -- deprecated function
function getScopeGroupPredicate(scope) {
    /* tslint:disable no-console */
    console.warn(`"getScopeGroupPredicate(query)" is deprecated. Please use "getGroupPredicate(qyr)`);
    const isGroupPredicate = (predicate) => !!predicate.group;
    const groupFilter = scope.filters.find((f) => f.predicates.find(isGroupPredicate));
    return groupFilter && groupFilter.predicates.find(isGroupPredicate);
}
/**
 * Searches through an `IQuery` and retrieves the predicate with a `group` definition.
 * If there is no group predicate, returns `null`
 * @param query IQuery to search
 * @returns
 */
function getGroupPredicate(query) {
    const predicate = "group";
    const expandedQuery = expandPortalQuery(query);
    const isTargetPredicate = (p) => !!p[predicate];
    const filter = expandedQuery.filters.find((f) => f.predicates.find(isTargetPredicate));
    return filter && filter.predicates.find(isTargetPredicate);
}
/**
 * Determines the canonical siteRelative link for a search result.
 *
 * We need to pass in `site` specifically for Hub Page items. Unfortunately
 * for us, Hub Page items have their canonical slug stored in the corresponding
 * site's data.json, not within the Hub Page item itself.
 *
 * NOTE: The slugs generated by indexer for Hub Page items are not canonical
 * and should not be used for link generation.
 *
 * @param searchResult the search result we're calculating the link for
 * @param site IHubSite that is related to the result
 * @returns a canonical siteRelative link
 */
function getResultSiteRelativeLink(searchResult, site) {
    var _a;
    const { id, type, typeKeywords } = searchResult;
    let siteRelativeLink = (_a = searchResult.links) === null || _a === void 0 ? void 0 : _a.siteRelative;
    if (siteRelativeLink && (0, internalContentUtils_1.isPageType)(type, typeKeywords)) {
        const pages = (site === null || site === void 0 ? void 0 : site.pages) || [];
        const targetPage = pages.find((p) => p.id === id);
        const slug = targetPage === null || targetPage === void 0 ? void 0 : targetPage.slug;
        if (slug) {
            siteRelativeLink = siteRelativeLink.replace(id, slug);
        }
    }
    return siteRelativeLink;
}
/**
 * Adds default predicates for item target entity
 *
 * @param query IQuery to search items
 * @returns a cloned copy of the query object with default item search predicates
 */
function addDefaultItemSearchPredicates(query) {
    const queryWithDefaultItemPredicates = (0, util_1.cloneObject)(query);
    const defaultPredicates = {
        // 'Code Attachment' is an old AGO type that has
        // been defunct for some time, so add this predicate
        // to all catalog filter to omit 'Code Attachment' items
        // from search results
        predicates: [{ type: { not: ["Code Attachment"] } }],
    };
    queryWithDefaultItemPredicates.filters.push(defaultPredicates);
    return queryWithDefaultItemPredicates;
}
/**
 * Returns the size in kilobytes of a query string or a SearchQueryBuilder.
 * This is used to later determine if a query is too large or almost too large to be sent to the server.
 * @param query
 * @returns
 */
function getKilobyteSizeOfQuery(query) {
    // convert query to string if it isn't already
    const queryString = typeof query === "string" ? query : query.toParam();
    // get the size of the query string using the TextEncoder api
    const encoder = new TextEncoder();
    const encodedString = encoder.encode(queryString);
    const sizeInBytes = encodedString.length;
    const sizeInKB = sizeInBytes / 1024; // Convert bytes to kilobytes
    return sizeInKB;
}
/**
 * Expand an item IQuery for portal by applying well-known filters and predicates,
 * and then expanding all the predicates into IMatchOption objects.
 * @param query `IQuery` to expand
 * @returns IQuery
 */
function expandPortalQuery(query) {
    // Expand well-known filterGroups
    const updatedQuery = (0, applyWellKnownItemPredicates_1.applyWellKnownItemPredicates)(query);
    // Expand the individual predicates in each filter
    return (0, expandPredicates_1.expandPredicates)(updatedQuery);
}
//# sourceMappingURL=utils.js.map