// (C) 2021-2025 GoodData Corporation
import { walkLayout } from "@gooddata/sdk-backend-spi";
import { isDrillToInsight, isInsightWidget, isVisualizationSwitcherWidget, } from "@gooddata/sdk-model";
const getReferencesFromInsightWidget = (widget) => {
    const insightRefs = [];
    if (isInsightWidget(widget)) {
        insightRefs.push(widget.insight);
        widget.drills.forEach((drill) => {
            if (isDrillToInsight(drill)) {
                insightRefs.push(drill.target);
            }
        });
    }
    return insightRefs;
};
const getReferencesFromVisualizationSwitcherWidget = (widget) => {
    const insightRefs = [];
    if (isVisualizationSwitcherWidget(widget)) {
        widget.visualizations.forEach((visualization) => {
            insightRefs.push(visualization.insight);
            visualization.drills.forEach((drill) => {
                if (isDrillToInsight(drill)) {
                    insightRefs.push(drill.target);
                }
            });
        });
    }
    return insightRefs;
};
export function insightReferences(layout) {
    const insightRefsFromWidgets = [];
    if (layout) {
        walkLayout(layout, {
            widgetCallback: (widget) => {
                if (isInsightWidget(widget)) {
                    insightRefsFromWidgets.push(...getReferencesFromInsightWidget(widget));
                }
                if (isVisualizationSwitcherWidget(widget)) {
                    insightRefsFromWidgets.push(...getReferencesFromVisualizationSwitcherWidget(widget));
                }
            },
        });
    }
    return insightRefsFromWidgets;
}
/**
 * Extracts insight references from a dashboard, including all tabs if present.
 */
export function insightReferencesFromDashboard(dashboard) {
    const insightRefsFromWidgets = [];
    const collectInsightRefs = (widget) => {
        if (isInsightWidget(widget)) {
            insightRefsFromWidgets.push(...getReferencesFromInsightWidget(widget));
        }
        if (isVisualizationSwitcherWidget(widget)) {
            insightRefsFromWidgets.push(...getReferencesFromVisualizationSwitcherWidget(widget));
        }
    };
    // Walk through tabs if they exist
    if (dashboard.tabs && dashboard.tabs.length > 0) {
        dashboard.tabs.forEach((tab) => {
            if (tab.layout) {
                walkLayout(tab.layout, {
                    widgetCallback: collectInsightRefs,
                });
            }
        });
    }
    // Also walk through root layout for backwards compatibility
    if (dashboard.layout) {
        walkLayout(dashboard.layout, {
            widgetCallback: collectInsightRefs,
        });
    }
    return insightRefsFromWidgets;
}
//# sourceMappingURL=insightReferences.js.map