"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalize = normalize;
exports.denormalize = denormalize;
const normalizr_1 = require("normalizr");
const index_js_1 = require("../types/index.js");
const string_js_1 = require("./string.js");
const widgetSchema = new normalizr_1.schema.Entity('canvasWidgets', {}, { idAttribute: 'widgetId' });
widgetSchema.define({ children: [widgetSchema] });
const PAGE_WIDGET_ID = '0';
/**
 * Fixes invalid DSL from previous bugs on initial load.
 *  1. removes duplicate IDs
 *  2. de-duplicates identical Section and Canvas names because their names don't matter
 *  3. removes timers and stateVars from the page widget, as they are processed separately
 */
function normalize(dsl) {
    if (!dsl)
        return { entities: { canvasWidgets: {} }, result: '' };
    const flattenedWidgets = {};
    const previouslySeenCanvasNames = new Set();
    function flattenWidget(widget) {
        if (flattenedWidgets[widget.widgetId])
            return;
        if (widget.children) {
            flattenedWidgets[widget.widgetId] = {
                ...widget,
                children: Array.from(new Set(widget.children?.map((child) => child.widgetId)))
            };
        }
        else {
            flattenedWidgets[widget.widgetId] = widget;
        }
        if (widget.widgetId === PAGE_WIDGET_ID) {
            // Extracted separately
            delete widget.stateVars;
            delete widget.timers;
            delete widget.events;
        }
        if ((widget.type === index_js_1.WidgetTypes.CANVAS_WIDGET || widget.type === index_js_1.WidgetTypes.SECTION_WIDGET) &&
            previouslySeenCanvasNames.has(widget.widgetName)) {
            const newName = (0, string_js_1.getNextEntityName)(widget.widgetName, Array.from(previouslySeenCanvasNames));
            flattenedWidgets[widget.widgetId].widgetName = newName;
            previouslySeenCanvasNames.add(newName);
        }
        else {
            previouslySeenCanvasNames.add(widget.widgetName);
        }
        if (widget.children) {
            widget.children.forEach(flattenWidget);
        }
    }
    flattenWidget(dsl);
    return {
        entities: { canvasWidgets: flattenedWidgets },
        result: dsl.widgetId
    };
}
function denormalize(pageWidgetId, entities) {
    return (0, normalizr_1.denormalize)(pageWidgetId, widgetSchema, entities);
}
//# sourceMappingURL=normalize.js.map