"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hubItemEntityFromEditor = void 0;
const Catalog_1 = require("../../search/Catalog");
const slugs_1 = require("../../items/_internal/slugs");
const initCatalogOnEntityCreate_1 = require("../../search/initCatalogOnEntityCreate");
const util_1 = require("../../util");
const setMetricAndDisplay_1 = require("../schemas/internal/metrics/setMetricAndDisplay");
const editorToMetric_1 = require("../../metrics/editorToMetric");
const doesResourceExist_1 = require("../../resources/doesResourceExist");
const removeResource_1 = require("../../resources/removeResource");
const upsertResource_1 = require("../../resources/upsertResource");
const getTemplate_1 = require("./getTemplate");
/**
 * Convert editor values back into an IHubItemEntity,
 * performing any pre-save operations/XHRs/transforms.
 * @param editor - the editor object to convert
 * @param context - contextual portal & auth information
 */
const hubItemEntityFromEditor = async (editor, context) => {
    var _a, _b, _c;
    let catalog;
    let thumbnailCache;
    // 1. extract the ephemeral props we graft onto the
    // editor for later use
    const _thumbnail = editor._thumbnail;
    const _catalogSetup = editor._catalogSetup;
    const _layoutSetup = editor._layoutSetup;
    const _metric = editor._metric;
    const _slug = editor._slug;
    const _featuredImage = (_a = editor.view) === null || _a === void 0 ? void 0 : _a.featuredImage;
    // 2. remove the ephemeral props we graft onto the editor
    delete editor._groups;
    delete editor._thumbnail;
    (_b = editor.view) === null || _b === void 0 ? true : delete _b.featuredImage;
    delete editor._layoutSetup;
    delete editor._metric;
    delete editor._catalogSetup;
    delete editor._slug;
    let entity = (0, util_1.cloneObject)(editor);
    // 3. ensure orgUrlKey is set and downcased
    entity.orgUrlKey = editor.orgUrlKey
        ? editor.orgUrlKey
        : context.portal.urlKey || "";
    entity.orgUrlKey = entity.orgUrlKey.toLowerCase();
    // 4. copy the configured location extent up one level
    // on the entity.
    entity.extent = (_c = editor.location) === null || _c === void 0 ? void 0 : _c.extent;
    // 5. Perform pre-save operations using the ephemeral
    // properties that were extracted above.
    // a. ensure the slug is truncated
    if (_slug) {
        // ensure the slug is truncated
        entity.slug = (0, slugs_1.truncateSlug)(_slug, entity.orgUrlKey);
    }
    else {
        // if no slug is passed in, save an empty string as
        // the slug, so that it is not saved as the orgUrlKey
        // truncated with an empty string
        entity.slug = "";
    }
    // b. conditionally set the thumbnailCache to
    // ensure that the configured thumbnail is updated
    // on the next save
    if (_thumbnail) {
        if (_thumbnail.blob) {
            thumbnailCache = {
                file: _thumbnail.blob,
                filename: _thumbnail.fileName,
                clear: false,
            };
        }
        else {
            thumbnailCache = {
                clear: true,
            };
        }
    }
    // c. conditionally upsert or remove the configured
    // featured image
    if (_featuredImage) {
        let featuredImageUrl = null;
        if (_featuredImage.blob) {
            featuredImageUrl = await (0, upsertResource_1.upsertResource)(entity.id, entity.owner, _featuredImage.blob, "featuredImage.png", context.userRequestOptions);
        }
        else if (await (0, doesResourceExist_1.doesResourceExist)(entity.id, "featuredImage.png", context.userRequestOptions)) {
            await (0, removeResource_1.removeResource)(entity.id, "featuredImage.png", entity.owner, context.userRequestOptions);
        }
        entity.view = Object.assign(Object.assign({}, entity.view), { featuredImageUrl });
    }
    // d. handle catalog setup
    if ((_catalogSetup === null || _catalogSetup === void 0 ? void 0 : _catalogSetup.type) === "newGroup" ||
        ((_catalogSetup === null || _catalogSetup === void 0 ? void 0 : _catalogSetup.type) === "existingGroup" && _catalogSetup.groupId)) {
        entity.catalog = await (0, initCatalogOnEntityCreate_1.initCatalogOnEntityCreate)(entity, _catalogSetup, context);
        catalog = Catalog_1.Catalog.fromJson(entity.catalog, context);
    }
    // e. handle metrics
    if (_metric && Object.keys(_metric).length) {
        const metricId = _metric.metricId ||
            (0, util_1.createId)((0, util_1.camelize)(`${_metric.cardTitle}_`));
        const { metric, displayConfig } = (0, editorToMetric_1.editorToMetric)(_metric, metricId, {
            metricName: _metric.cardTitle,
        });
        entity = (0, setMetricAndDisplay_1.setMetricAndDisplay)(entity, metric, displayConfig);
    }
    // f. handle layout setups in sites and pages
    // _layoutSetup is optional, if not present we
    // simply do not modify the layout
    // It should only be present on new entities
    // being created via the add-content workflow
    // where a layout choice is offered
    if (_layoutSetup) {
        if (_layoutSetup.layout === "simple") {
            entity.layout = await (0, getTemplate_1.getTemplate)("simpleSiteOrPageLayout", context);
        }
        else {
            entity.layout = await (0, getTemplate_1.getTemplate)("blankSiteOrPageLayout", context);
        }
    }
    return Object.assign(Object.assign({ entity }, (thumbnailCache && { thumbnailCache })), (catalog && { _catalog: catalog }));
};
exports.hubItemEntityFromEditor = hubItemEntityFromEditor;
//# sourceMappingURL=hubItemEntityFromEditor.js.map