"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchItem = fetchItem;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const slugs_1 = require("./slugs");
const slugConverters_1 = require("./_internal/slugConverters");
const slugs_2 = require("./_internal/slugs");
const slugs_3 = require("../content/slugs");
/**
 * Fetch an item by its identifier
 * @param identifier item id or slug, which may or may not include the org key
 * @param requestOptions
 */
function fetchItem(identifier, requestOptions) {
    const { id, slug, orgKey } = (0, slugs_2.parseIdentifier)(identifier);
    if (id) {
        // use the id to fetch the item
        return (0, arcgis_rest_portal_1.getItem)(id, requestOptions);
    }
    // we'll have to look up by slug
    // first, ensure the slug has the org key
    const fullyQualifiedSlug = (0, slugs_3.addContextToSlug)(slug, orgKey || requestOptions.siteOrgKey);
    const slugKeyword = (0, slugConverters_1.uriSlugToKeywordSlug)(fullyQualifiedSlug);
    return (0, slugs_1.findItemsBySlug)({ slug: slugKeyword }, requestOptions)
        .then((results) => {
        if (results.length) {
            return results;
        }
        else {
            // we had a bug where page slugs could have been stored without the org url key prefix
            // we decided to fall back to looking for them without the prefix
            const slugWithoutOrgKey = slugKeyword.split("|").slice(1).join("|");
            return (0, slugs_1.findItemsBySlug)({ slug: slugWithoutOrgKey }, requestOptions);
        }
    })
        .then((results) => {
        if (results.length) {
            // search results only include a subset of properties of the item, so
            // issue a subsequent call to getItem to get the full item details
            return (0, arcgis_rest_portal_1.getItem)(results[0].id, requestOptions);
        }
        else {
            return null;
        }
    });
}
//# sourceMappingURL=fetch.js.map