"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPage = createPage;
exports.updatePage = updatePage;
exports.fetchPage = fetchPage;
exports.convertModelToPage = convertModelToPage;
exports.convertItemToPage = convertItemToPage;
exports.deletePage = deletePage;
exports.enrichPageSearchResult = enrichPageSearchResult;
const get_family_1 = require("../content/get-family");
const internalContentUtils_1 = require("../content/_internal/internalContentUtils");
const _enrichments_1 = require("../items/_enrichments");
const parseInclude_1 = require("../search/_internal/parseInclude");
const util_1 = require("../util");
const slugs_1 = require("../items/slugs");
const PropertyMapper_1 = require("../core/_internal/PropertyMapper");
const getPropertyMap_1 = require("./_internal/getPropertyMap");
const computeProps_1 = require("./_internal/computeProps");
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const defaults_1 = require("./defaults");
const ensureUniqueEntitySlug_1 = require("../items/_internal/ensureUniqueEntitySlug");
const computeLinks_1 = require("./_internal/computeLinks");
const fetch_1 = require("../items/fetch");
const createModel_1 = require("../models/createModel");
const fetchModelFromItem_1 = require("../models/fetchModelFromItem");
const getModel_1 = require("../models/getModel");
const updateModel_1 = require("../models/updateModel");
const get_prop_1 = require("../objects/get-prop");
const map_by_1 = require("../utils/map-by");
/**
 * @private
 * Create a new Hub Page item
 *
 * Minimal properties are name and org
 *
 * @param partialPage
 * @param requestOptions
 */
async function createPage(partialPage, requestOptions) {
    // merge incoming with the default
    // this expansion solves the typing somehow
    const page = Object.assign(Object.assign({}, defaults_1.DEFAULT_PAGE), partialPage);
    // ensure orgUrlKey is lowercase
    page.orgUrlKey = page.orgUrlKey.toLowerCase();
    // Create a slug from the title if one is not passed in
    if (!page.slug) {
        page.slug = (0, slugs_1.constructSlug)(page.name, page.orgUrlKey);
    }
    // Ensure slug is  unique
    await (0, ensureUniqueEntitySlug_1.ensureUniqueEntitySlug)(page, requestOptions);
    // Map page object onto a default page Model
    const mapper = new PropertyMapper_1.PropertyMapper((0, getPropertyMap_1.getPropertyMap)());
    // create model from object, using the default model as a starting point
    let model = mapper.entityToStore(page, (0, util_1.cloneObject)(defaults_1.DEFAULT_PAGE_MODEL));
    // create the item
    model = await (0, createModel_1.createModel)(model, requestOptions);
    // map the model back into a IHubPage
    let newPage = mapper.storeToEntity(model, {});
    newPage = (0, computeProps_1.computeProps)(model, newPage, requestOptions);
    // and return it
    return newPage;
}
/**
 * @private
 * Update a Hub Page
 * @param page
 * @param requestOptions
 */
async function updatePage(page, requestOptions) {
    // verify that the slug is unique, excluding the current page
    await (0, ensureUniqueEntitySlug_1.ensureUniqueEntitySlug)(page, requestOptions);
    // get the backing item & data
    const model = await (0, getModel_1.getModel)(page.id, requestOptions);
    // create the PropertyMapper
    const mapper = new PropertyMapper_1.PropertyMapper((0, getPropertyMap_1.getPropertyMap)());
    // Note: Although we are fetching the model, and applying changes onto it,
    // we are not attempting to handle "concurrent edit" conflict resolution
    // but this is where we would apply that sort of logic
    const modelToUpdate = mapper.entityToStore(page, model);
    // update the backing item
    const updatedModel = await (0, updateModel_1.updateModel)(modelToUpdate, requestOptions);
    // now map back into a page and return that
    let updatedPage = mapper.storeToEntity(updatedModel, page);
    updatedPage = (0, computeProps_1.computeProps)(model, updatedPage, requestOptions);
    // the casting is needed because modelToObject returns a `Partial<T>`
    // where as this function returns a `T`
    return updatedPage;
}
/**
 * @private
 * Get a Hub Page by id or slug
 * @param identifier item id or slug
 * @param requestOptions
 */
async function fetchPage(identifier, requestOptions) {
    const item = await (0, fetch_1.fetchItem)(identifier, requestOptions);
    return item ? convertItemToPage(item, requestOptions) : null;
}
/**
 * @internal
 * Convert an IModel for a Hub Page Item into an IHubPage
 * @param model
 * @param requestOptions
 * @returns
 */
function convertModelToPage(model, requestOptions) {
    const mapper = new PropertyMapper_1.PropertyMapper((0, getPropertyMap_1.getPropertyMap)());
    const prj = mapper.storeToEntity(model, {});
    return (0, computeProps_1.computeProps)(model, prj, requestOptions);
}
/**
 * @private
 * Convert an Hub Page Item into a Hub Page, fetching any additional
 * information that may be required
 * @param item
 * @param auth
 * @returns
 */
async function convertItemToPage(item, requestOptions) {
    const model = await (0, fetchModelFromItem_1.fetchModelFromItem)(item, requestOptions);
    // TODO: In the future we will handle the boundary fetching from resource
    return convertModelToPage(model, requestOptions);
}
/**
 * @private
 * Remove a Hub Page
 * @param id
 * @param requestOptions
 */
async function deletePage(id, requestOptions) {
    const ro = Object.assign(Object.assign({}, requestOptions), { id });
    await (0, arcgis_rest_portal_1.removeItem)(ro);
    return;
}
/**
 * Fetch Page specific Enrichments
 * @param item
 * @param include
 * @param requestOptions
 * @returns
 */
async function enrichPageSearchResult(item, include, requestOptions) {
    // Create the basic structure
    const result = {
        access: item.access,
        id: item.id,
        type: item.type,
        name: item.title,
        owner: item.owner,
        typeKeywords: item.typeKeywords,
        tags: item.tags,
        categories: item.categories,
        summary: item.snippet || item.description,
        createdDate: new Date(item.created),
        createdDateSource: "item.created",
        updatedDate: new Date(item.modified),
        updatedDateSource: "item.modified",
        family: (0, get_family_1.getFamily)(item.type),
        links: {
            self: "not-implemented",
            siteRelative: "not-implemented",
            thumbnail: "not-implemented",
        },
        location: (0, internalContentUtils_1.deriveLocationFromItem)(item),
        rawResult: item,
    };
    // default includes
    const DEFAULTS = [];
    // merge includes
    include = [...DEFAULTS, ...include].filter(util_1.unique);
    // Parse the includes into a valid set of enrichments
    const specs = include.map(parseInclude_1.parseInclude);
    // Extract out the low-level enrichments needed
    const enrichments = (0, map_by_1.mapBy)("enrichment", specs).filter(util_1.unique);
    // fetch the enrichments
    let enriched = {};
    if (enrichments.length) {
        // TODO: Look into caching for the requests in fetchItemEnrichments
        enriched = await (0, _enrichments_1.fetchItemEnrichments)(item, enrichments, requestOptions);
    }
    // map the enriched props onto the result
    specs.forEach((spec) => {
        result[spec.prop] = (0, get_prop_1.getProp)(enriched, spec.path);
    });
    // Handle links
    result.links = (0, computeLinks_1.computeLinks)(item, requestOptions);
    return result;
}
//# sourceMappingURL=HubPages.js.map