"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.matchByTitleSearch = matchByTitleSearch;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const getItemTypeFromMatchableType_1 = require("./getItemTypeFromMatchableType");
const get_with_default_1 = require("../../objects/get-with-default");
/**
 * Match by a title search
 * Handles searching by title: "%identifier.replace('-', ' ')%" and type: {type}
 * @param type
 * @param identifier
 * @param context
 * @returns
 */
async function matchByTitleSearch(type, identifier, context) {
    const result = {
        identifier,
        type,
        matcher: "title-search",
        num: 0,
        matches: [],
    };
    let filter = `title:"%${identifier.replace(/-/g, " ")}%"`;
    // if the type is specific enough, add it to the Filter, accounting for Enterprise
    const itemType = (0, getItemTypeFromMatchableType_1.getItemTypeFromMatchableType)(type, !!context.isPortal);
    if (itemType) {
        // add type to the filter
        filter = `${filter} AND type:"${itemType}"`;
    }
    const opts = {
        // This uses q so it's a fuzzy match
        q: filter,
    };
    // Add auth or portal to the search options
    if (context.requestOptions.authentication) {
        opts.authentication = context.requestOptions.authentication;
    }
    else {
        opts.portal = context.requestOptions.portal;
    }
    // execute the search against the portal api
    const response = await (0, arcgis_rest_portal_1.searchItems)(opts);
    // Convert results to IMatch[]
    const matches = response.results.map((item) => ({
        id: item.id,
        type: item.type,
        name: item.title,
        identifier: (0, get_with_default_1.getWithDefault)(item, "properties.slug", item.id),
    }));
    result.num = matches.length;
    result.matches = matches;
    return result;
}
//# sourceMappingURL=matchByTitleSearch.js.map