// (C) 2021-2026 GoodData Corporation
import { areObjRefsEqual, objRefToString, widgetId, widgetRef, widgetUri, } from "@gooddata/sdk-model";
import { getDashboardInsightMenuButtonId } from "../../../_staging/accessibility/elementId.js";
import { getDrillOriginLocalIdentifier } from "../../../_staging/drills/drillingUtils.js";
const openScheduleEmailDialog = (state, action) => {
    const { widgetRef, schedule, openedFrom } = action.payload;
    state.scheduleEmailDialog.open = true;
    if (schedule) {
        state.scheduleEmailDialog.context = {
            ...(state.scheduleEmailDialog.context || {}),
            schedule,
        };
    }
    if (widgetRef) {
        state.scheduleEmailDialog.context = {
            ...(state.scheduleEmailDialog.context || {}),
            widgetRef,
        };
        if (openedFrom === "widget") {
            const returnFocusTo = getDashboardInsightMenuButtonId(objRefToString(widgetRef));
            state.scheduleEmailDialog.returnFocusTo = returnFocusTo;
        }
    }
    if (openedFrom === "dashboard") {
        state.scheduleEmailDialog.returnFocusTo = undefined;
    }
};
const closeScheduleEmailDialog = (state) => {
    state.scheduleEmailDialog.open = false;
    state.scheduleEmailDialog.context = undefined;
};
const setScheduleEmailDialogDefaultAttachment = (state, action) => {
    state.scheduleEmailDialog.defaultAttachmentRef = action.payload;
};
const resetScheduleEmailDialogDefaultAttachment = (state) => {
    state.scheduleEmailDialog.defaultAttachmentRef = undefined;
};
const openScheduleEmailManagementDialog = (state, action) => {
    const { widgetRef, openedFrom } = action.payload;
    state.scheduleEmailManagementDialog.open = true;
    state.automationsManagement.invalidationId = 0;
    if (widgetRef) {
        state.scheduleEmailManagementDialog.context = {
            widgetRef,
        };
        if (openedFrom === "widget") {
            const returnFocusTo = getDashboardInsightMenuButtonId(objRefToString(widgetRef));
            state.scheduleEmailDialog.returnFocusTo = returnFocusTo;
        }
    }
    if (openedFrom === "dashboard") {
        state.scheduleEmailDialog.returnFocusTo = undefined;
    }
};
const closeScheduleEmailManagementDialog = (state) => {
    state.scheduleEmailManagementDialog.open = false;
    state.scheduleEmailManagementDialog.context = undefined;
};
const openAlertingManagementDialog = (state, action) => {
    const { widgetRef, openedFrom } = action.payload ?? {};
    state.alertsManagementDialog.open = true;
    state.automationsManagement.invalidationId = 0;
    if (widgetRef) {
        state.alertsManagementDialog.context = {
            widgetRef,
        };
        if (openedFrom === "widget") {
            const returnFocusTo = getDashboardInsightMenuButtonId(objRefToString(widgetRef));
            state.alertsDialog.returnFocusTo = returnFocusTo;
        }
    }
    if (openedFrom === "dashboard") {
        state.alertsDialog.returnFocusTo = undefined;
    }
};
const closeAlertingManagementDialog = (state) => {
    state.alertsManagementDialog.open = false;
    state.alertsManagementDialog.context = undefined;
};
const openAlertingDialog = (state, action) => {
    state.alertsDialog.open = true;
    state.alertsDialog.context = action.payload;
};
const closeAlertingDialog = (state) => {
    state.alertsDialog.open = false;
    state.alertsDialog.context = undefined;
};
const openSaveAsDialog = (state) => {
    state.saveAsDialog.open = true;
};
const closeSaveAsDialog = (state) => {
    state.saveAsDialog.open = false;
};
const openSettingsDialog = (state) => {
    state.settingsDialog.open = true;
};
const closeSettingsDialog = (state) => {
    state.settingsDialog.open = false;
};
const openDensityDialog = (state) => {
    state.densityDialog.open = true;
};
const closeDensityDialog = (state) => {
    state.densityDialog.open = false;
};
const setDensity = (state, action) => {
    state.density = action.payload;
};
const openShareDialog = (state) => {
    state.shareDialog.open = true;
};
const closeShareDialog = (state) => {
    state.shareDialog.open = false;
};
const openDeleteDialog = (state) => {
    state.deleteDialog.open = true;
};
const closeDeleteDialog = (state) => {
    state.deleteDialog.open = false;
};
const openWidgetDeleteDialog = (state, action) => {
    state.widgetDeleteDialog.open = true;
    state.widgetDeleteDialog.widgetRef = action.payload;
};
const closeWidgetDeleteDialog = (state) => {
    state.widgetDeleteDialog.open = false;
    state.widgetDeleteDialog.widgetRef = undefined;
};
const toggleFilterViewsDialog = (state, action) => {
    state.filterViews = {
        open: action.payload?.open ?? !state.filterViews.open,
        mode: action.payload?.mode ?? "list",
    };
};
const openKpiDeleteDialog = (state, action) => {
    state.kpiDeleteDialog.widgetCoordinates = action.payload;
};
const closeKpiDeleteDialog = (state) => {
    state.kpiDeleteDialog.widgetCoordinates = undefined;
};
const setFilterBarExpanded = (state, action) => {
    state.filterBar.expanded = action.payload;
};
const openKpiAlertDialog = (state, action) => {
    state.kpiAlerts.openedWidgetRef = action.payload;
};
const closeKpiAlertDialog = (state) => {
    state.kpiAlerts.openedWidgetRef = undefined;
};
const openCancelEditModeDialog = (state) => {
    state.cancelEditModeDialog.open = true;
};
const closeCancelEditModeDialog = (state) => {
    state.cancelEditModeDialog.open = false;
};
const highlightKpiAlert = (state, action) => {
    state.kpiAlerts.highlightedWidgetRef = action.payload;
};
const setMenuButtonItemsVisibility = (state, action) => {
    state.menuButton.itemsVisibility = action.payload;
};
const selectWidget = (state, action) => {
    state.selectedWidgetRef = action.payload;
};
const clearWidgetSelection = (state) => {
    state.selectedWidgetRef = undefined;
};
const setConfigurationPanelOpened = (state, action) => {
    state.configurationPanelOpened = action.payload;
};
const setWidgetDateDatasetAutoSelect = (state, action) => {
    state.widgetDateDatasetAutoSelect = action.payload;
};
const requestInsightListUpdate = (state) => {
    state.insightListLastUpdateRequested = +new Date();
};
const setWidgetLoadingAdditionalDataStarted = (state, action) => {
    state.widgetsLoadingAdditionalData.push(action.payload);
};
const setWidgetLoadingAdditionalDataStopped = (state, action) => {
    state.widgetsLoadingAdditionalData = state.widgetsLoadingAdditionalData.filter((item) => !areObjRefsEqual(item, action.payload));
};
const setFilterAttributeSelectionOpen = (state, action) => {
    state.filterAttributeSelectionOpen = action.payload;
};
const selectFilterIndex = (state, action) => {
    state.selectedFilterIndex = action.payload;
};
const clearFilterIndexSelection = (state) => {
    state.selectedFilterIndex = undefined;
};
const setActiveSection = (state, action) => {
    state.activeSection = action.payload;
};
const clearActiveSection = (state) => {
    state.activeSection = undefined;
};
const resetInvalidDrillWidgetRefs = (state) => {
    state.drillValidationMessages.invalidDrillWidgetRefs = [];
};
const resetSanitizedDrillWidgetRefs = (state) => {
    state.drillValidationMessages.sanitizedDrillWidgetRefs = [];
};
const resetAllInvalidCustomUrlDrillParameterWidgets = (state) => {
    state.drillValidationMessages.invalidCustomUrlDrillParameterWidgets = [];
};
const resetAllInvalidCustomUrlDrillParameterWidgetsWarnings = (state) => {
    state.drillValidationMessages.invalidCustomUrlDrillParameterWidgets =
        state.drillValidationMessages.invalidCustomUrlDrillParameterWidgets.map((item) => {
            return { ...item, showMessage: false };
        });
};
const addInvalidDrillWidgetRefs = (state, action) => {
    action.payload.forEach((toAdd) => {
        if (!state.drillValidationMessages.invalidDrillWidgetRefs.some((existing) => areObjRefsEqual(existing, toAdd))) {
            state.drillValidationMessages.invalidDrillWidgetRefs.push(toAdd);
        }
    });
};
const addSanitizedDrillWidgetRefs = (state, action) => {
    action.payload.forEach((toAdd) => {
        if (!state.drillValidationMessages.sanitizedDrillWidgetRefs.some((existing) => areObjRefsEqual(existing, toAdd))) {
            state.drillValidationMessages.sanitizedDrillWidgetRefs.push(toAdd);
        }
    });
};
const setInvalidCustomUrlDrillParameterWidgets = (state, action) => {
    action.payload.forEach((item) => {
        const existingIndex = state.drillValidationMessages.invalidCustomUrlDrillParameterWidgets.findIndex((i) => i.widgetId === widgetId(item.widget));
        const itemToStore = {
            drillsWithInvalidParametersLocalIds: item.invalidDrills.map(getDrillOriginLocalIdentifier),
            widgetId: widgetId(item.widget),
            widgetRef: widgetRef(item.widget),
            widgetUri: widgetUri(item.widget),
            showMessage: true,
        };
        if (existingIndex >= 0) {
            state.drillValidationMessages.invalidCustomUrlDrillParameterWidgets[existingIndex] = itemToStore;
        }
        else {
            state.drillValidationMessages.invalidCustomUrlDrillParameterWidgets.push(itemToStore);
        }
    });
};
const resetInvalidCustomUrlDrillParameterWidget = (state, action) => {
    action.payload.forEach((widget) => {
        const existingIndex = state.drillValidationMessages.invalidCustomUrlDrillParameterWidgets.findIndex((i) => i.widgetId === widgetId(widget));
        if (existingIndex >= 0) {
            state.drillValidationMessages.invalidCustomUrlDrillParameterWidgets.splice(existingIndex, 1);
        }
    });
};
const removeInvalidDrillWidgetRefs = (state, action) => {
    state.drillValidationMessages.invalidDrillWidgetRefs =
        state.drillValidationMessages.invalidDrillWidgetRefs.filter((existing) => !action.payload.some((toRemove) => areObjRefsEqual(toRemove, existing)));
};
const removeSanitizedDrillWidgetRefs = (state, action) => {
    state.drillValidationMessages.sanitizedDrillWidgetRefs =
        state.drillValidationMessages.sanitizedDrillWidgetRefs.filter((existing) => !action.payload.some((toRemove) => areObjRefsEqual(toRemove, existing)));
};
const setDraggingWidgetSource = (state, action) => {
    state.draggingWidgetSource = action.payload;
};
const clearDraggingWidgetSource = (state) => {
    state.draggingWidgetSource = undefined;
};
const setDraggingWidgetTarget = (state, action) => {
    const { path, triggeringDropZoneType } = action.payload;
    state.draggingWidgetTarget = path;
    state.draggingWidgetTriggeringDropZoneType = triggeringDropZoneType;
    state.activeSection = {
        parent: path.length > 1 ? path.slice(0, -1) : undefined, // cut last item out to get parent of the item of section with sectionIndex used below
        sectionIndex: path[path.length - 1].sectionIndex, // use sectionIndex from the last item
    };
};
const clearDraggingWidgetTarget = (state) => {
    state.draggingWidgetTarget = undefined;
    state.draggingWidgetTriggeringDropZoneType = undefined;
    state.activeSection = undefined;
};
const setWidgetsOverlay = (state, action) => {
    state.widgetsOverlay = action.payload;
};
const toggleWidgetsOverlay = (state, action) => {
    const { visible, refs } = action.payload;
    refs.forEach((ref) => {
        if (!ref) {
            return;
        }
        const refId = objRefToString(ref);
        const overlay = (state.widgetsOverlay[refId] = state.widgetsOverlay[refId] || {
            showOverlay: visible,
        });
        overlay.showOverlay = visible;
    });
};
const hideAllWidgetsOverlay = (state) => {
    state.widgetsOverlay = Object.keys(state.widgetsOverlay).reduce((prev, key) => {
        return {
            ...prev,
            [key]: {
                ...state.widgetsOverlay[key],
                showOverlay: false,
            },
        };
    }, {});
};
const changeIgnoreExecutionTimestamp = (state, action) => {
    state.ignoreExecutionTimestamp = action.payload;
};
const setIncompatibleDefaultFiltersOverrideMessage = (state) => {
    state.filterValidationMessages.incompatibleDefaultFiltersOverride = true;
};
const resetIncompatibleDefaultFiltersOverrideMessage = (state) => {
    state.filterValidationMessages.incompatibleDefaultFiltersOverride = false;
};
const invalidateAutomationItems = (state) => {
    state.automationsManagement.invalidationId += 1;
};
export const uiReducers = {
    openSettingsDialog,
    closeSettingsDialog,
    openDensityDialog,
    closeDensityDialog,
    setDensity,
    openScheduleEmailDialog,
    closeScheduleEmailDialog,
    setScheduleEmailDialogDefaultAttachment,
    resetScheduleEmailDialogDefaultAttachment,
    openScheduleEmailManagementDialog,
    closeScheduleEmailManagementDialog,
    openAlertingManagementDialog,
    closeAlertingManagementDialog,
    openAlertingDialog,
    closeAlertingDialog,
    openSaveAsDialog,
    closeSaveAsDialog,
    setFilterBarExpanded,
    closeKpiAlertDialog,
    openKpiAlertDialog,
    highlightKpiAlert,
    openShareDialog,
    closeShareDialog,
    openDeleteDialog,
    closeDeleteDialog,
    openKpiDeleteDialog,
    closeKpiDeleteDialog,
    setMenuButtonItemsVisibility,
    selectWidget,
    clearWidgetSelection,
    setConfigurationPanelOpened,
    setWidgetDateDatasetAutoSelect,
    requestInsightListUpdate,
    setWidgetLoadingAdditionalDataStarted,
    setWidgetLoadingAdditionalDataStopped,
    setFilterAttributeSelectionOpen,
    selectFilterIndex,
    clearFilterIndexSelection,
    setActiveSection,
    clearActiveSection,
    openCancelEditModeDialog,
    closeCancelEditModeDialog,
    resetInvalidDrillWidgetRefs,
    resetSanitizedDrillWidgetRefs,
    resetAllInvalidCustomUrlDrillParameterWidgets,
    resetAllInvalidCustomUrlDrillParameterWidgetsWarnings,
    addInvalidDrillWidgetRefs,
    addSanitizedDrillWidgetRefs,
    setInvalidCustomUrlDrillParameterWidgets,
    removeInvalidDrillWidgetRefs,
    removeSanitizedDrillWidgetRefs,
    resetInvalidCustomUrlDrillParameterWidget,
    setDraggingWidgetSource,
    clearDraggingWidgetSource,
    setDraggingWidgetTarget,
    clearDraggingWidgetTarget,
    toggleWidgetsOverlay,
    setWidgetsOverlay,
    hideAllWidgetsOverlay,
    toggleFilterViewsDialog,
    openWidgetDeleteDialog,
    closeWidgetDeleteDialog,
    changeIgnoreExecutionTimestamp,
    setIncompatibleDefaultFiltersOverrideMessage,
    resetIncompatibleDefaultFiltersOverrideMessage,
    invalidateAutomationItems,
};
