"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUpdatesInWidgets = getUpdatesInWidgets;
exports.updateNameInEntityMap = updateNameInEntityMap;
const lodash_1 = require("lodash");
const index_js_1 = require("../types/index.js");
const refactor_js_1 = require("./refactor.js");
const rename_js_1 = require("./rename.js");
const PAGE_WIDGET_ID = '0';
async function getUpdatesInWidgets({ widgets, oldName, newName, dataTree, extractPairs, namespace }) {
    let updates = [];
    for (const [widgetId, widget] of Object.entries(widgets)) {
        if (widget.widgetName === oldName) {
            updates.push({
                entityId: widgetId,
                propertyName: 'widgetName',
                propertyValue: newName
            });
            // if it's a table, rename in all of the cached columns (which aren't dynamic)
            if (widget.type === 'TABLE_WIDGET') {
                const tableWidget = widget;
                const cachedSettings = Object.keys(tableWidget.cachedColumnSettings ?? {}).reduce((accum, key) => {
                    Object.entries(tableWidget.cachedColumnSettings[key]).forEach(([k, v]) => {
                        if (typeof v === 'string') {
                            accum.push(`cachedColumnSettings.${key}.${k}`);
                        }
                    });
                    return accum;
                }, []);
                await Promise.all(cachedSettings.map(async (key) => {
                    const binding = (0, lodash_1.get)(widget, key);
                    const withNewName = await (0, refactor_js_1.refactorNameInString)({
                        value: binding,
                        oldName,
                        newName,
                        dataTree,
                        namespace,
                        extractPairs
                    });
                    if (binding !== withNewName) {
                        updates.push({
                            entityId: widgetId,
                            propertyName: key,
                            propertyValue: withNewName
                        });
                    }
                }));
            }
        }
        if (widget.dynamicBindingPathList) {
            await Promise.all(widget.dynamicBindingPathList.map(async ({ key }) => {
                const binding = (0, lodash_1.get)(widget, key);
                const withNewName = await (0, refactor_js_1.refactorNameInValue)({
                    oldValue: binding,
                    oldName,
                    newName,
                    dataTree,
                    namespace,
                    extractPairs
                });
                if (!(0, lodash_1.isEqual)(binding, withNewName)) {
                    updates.push({
                        entityId: widgetId,
                        propertyName: key,
                        propertyValue: withNewName
                    });
                }
            }));
        }
        if (widget.dynamicTriggerPathList) {
            const renameInTriggerStep = (0, rename_js_1.createTriggerStepRenamer)({
                oldName,
                newName,
                dataTree,
                addUpdate: (payload) => {
                    updates.push({
                        ...payload,
                        entityId: widgetId
                    });
                },
                extractEvaluationPairs: extractPairs,
                namespace
            });
            await Promise.all(widget.dynamicTriggerPathList.map(async ({ key }) => {
                const trigger = (0, lodash_1.get)(widget, key);
                if (!(0, lodash_1.isArray)(trigger)) {
                    return;
                }
                await Promise.all(trigger.map(async (step, index) => {
                    if (!(0, index_js_1.isValidStepDef)(step))
                        return;
                    await renameInTriggerStep(step, key, index);
                }));
            }));
        }
        // Canvas widgets also contain API response info
        if (widgetId === PAGE_WIDGET_ID && 'apis' in widget) {
            const apiUpdates = await updateNameInEntityMap({
                entityMap: widget.apis,
                parentId: widgetId,
                parentKey: 'apis',
                oldName,
                newName,
                dataTree,
                extractPairs,
                namespace
            });
            updates = [...updates, ...apiUpdates];
        }
    }
    return updates;
}
async function updateNameInEntityMap({ entityMap, parentKey, parentId = '', oldName, newName, dataTree, extractPairs, namespace }) {
    if (!entityMap)
        return [];
    const updates = [];
    const renameInTriggerStep = (0, rename_js_1.createTriggerStepRenamer)({
        oldName,
        newName,
        dataTree,
        addUpdate: (payload) => {
            updates.push({
                ...payload,
                entityId: parentId
            });
        },
        extractEvaluationPairs: extractPairs,
        namespace
    });
    if ('timerMap' in entityMap) {
        const timers = entityMap.timerMap;
        await Promise.all(Object.values(timers).map(async (timer) => {
            if (timer.name === oldName) {
                updates.push({
                    propertyName: `${parentKey}.timerMap.${timer.id}.name`,
                    propertyValue: newName,
                    entityId: timer.id
                });
            }
            await Promise.all(timer?.steps?.map(async (step, index) => {
                if (!(0, index_js_1.isValidStepDef)(step))
                    return;
                const mappedKey = `${parentKey}.timerMap.${timer.id}.steps`;
                await renameInTriggerStep(step, mappedKey, index);
            }));
        }));
    }
    else if ('apiMap' in entityMap) {
        const apis = entityMap.apiMap;
        for (const api of Object.values(apis)) {
            await Promise.all((api.dynamicTriggerPathList ?? [])?.map(async ({ key }) => {
                const mappedKey = `${parentKey}.apiMap.${api.id}.${key}`;
                const triggers = (0, lodash_1.get)(api, key, []);
                await Promise.all(triggers.map(async (step, index) => {
                    if (!(0, index_js_1.isValidStepDef)(step))
                        return;
                    await renameInTriggerStep(step, mappedKey, index);
                }));
            }));
        }
    }
    else if ('stateVarMap' in entityMap) {
        const stateVars = entityMap.stateVarMap;
        for (const stateVar of Object.values(stateVars)) {
            if (stateVar.name === oldName) {
                updates.push({
                    propertyName: `${parentKey}.stateVarMap.${stateVar.id}.name`,
                    propertyValue: newName,
                    entityId: stateVar.id
                });
            }
            if (stateVar.dynamicBindingPathList) {
                await Promise.all(stateVar.dynamicBindingPathList.map(async ({ key }) => {
                    const value = (0, lodash_1.get)(stateVar, key);
                    const newValue = await (0, refactor_js_1.refactorNameInValue)({
                        oldValue: value,
                        oldName,
                        newName,
                        dataTree,
                        namespace,
                        extractPairs
                    });
                    if (!(0, lodash_1.isEqual)(value, newValue)) {
                        updates.push({
                            entityId: parentId ?? stateVar.id,
                            propertyName: `${parentKey}.stateVarMap.${stateVar.id}.defaultValue`,
                            propertyValue: newValue
                        });
                    }
                }));
            }
        }
    }
    return updates;
}
//# sourceMappingURL=updates.js.map