import { Catalog } from "../../search/Catalog";
import { truncateSlug } from "../../items/_internal/slugs";
import { initCatalogOnEntityCreate } from "../../search/initCatalogOnEntityCreate";
import { camelize, cloneObject, createId } from "../../util";
import { setMetricAndDisplay } from "../schemas/internal/metrics/setMetricAndDisplay";
import { editorToMetric } from "../../metrics/editorToMetric";
import { doesResourceExist } from "../../resources/doesResourceExist";
import { removeResource } from "../../resources/removeResource";
import { upsertResource } from "../../resources/upsertResource";
import { getTemplate } from "./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
 */
export 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 = 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 = 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 upsertResource(entity.id, entity.owner, _featuredImage.blob, "featuredImage.png", context.userRequestOptions);
        }
        else if (await doesResourceExist(entity.id, "featuredImage.png", context.userRequestOptions)) {
            await 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 initCatalogOnEntityCreate(entity, _catalogSetup, context);
        catalog = Catalog.fromJson(entity.catalog, context);
    }
    // e. handle metrics
    if (_metric && Object.keys(_metric).length) {
        const metricId = _metric.metricId ||
            createId(camelize(`${_metric.cardTitle}_`));
        const { metric, displayConfig } = editorToMetric(_metric, metricId, {
            metricName: _metric.cardTitle,
        });
        entity = 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 getTemplate("simpleSiteOrPageLayout", context);
        }
        else {
            entity.layout = await getTemplate("blankSiteOrPageLayout", context);
        }
    }
    return Object.assign(Object.assign({ entity }, (thumbnailCache && { thumbnailCache })), (catalog && { _catalog: catalog }));
};
//# sourceMappingURL=hubItemEntityFromEditor.js.map