import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * Copyright (c) 2020-present, Goldman Sachs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { useApplicationStore } from '@finos/legend-application';
import { PlusIcon, PanelContent, PanelDropZone, BlankPanelPlaceholder, ControlledDropdownMenu, InputWithInlineValidation, MenuContent, MenuContentItem, SigmaIcon, CaretDownIcon, clsx, PanelEntryDropZonePlaceholder, ContextMenu, TimesIcon, useDragPreviewLayer, SortIcon, Dialog, CustomSelectorInput, WindowIcon, BasePopover, EditIcon, ModalHeader, Modal, ModalFooter, PanelFormSection, ModalFooterButton, PanelEntryDragHandle, PanelDnDEntry, PanelHeaderActionItem, PanelHeader, PanelHeaderActions, Panel, DragPreviewLayer, } from '@finos/legend-art';
import { assertErrorThrown, clone, deleteEntry, guaranteeNonNullable, } from '@finos/legend-shared';
import { observer } from 'mobx-react-lite';
import { forwardRef, useCallback, useRef, useState } from 'react';
import { useDrag, useDragLayer, useDrop, } from 'react-dnd';
import { QueryBuilderWindowColumnState, QueryBuilderTDS_WindowRankOperatorState, QueryBuilderTDS_WindowAggreationOperatorState, QUERY_BUILDER_WINDOW_COLUMN_DND_TYPE, WindowGroupByColumnSortByState, } from '../../stores/fetch-structure/tds/window/QueryBuilderWindowState.js';
import { QUERY_BUILDER_PROJECTION_COLUMN_DND_TYPE } from '../../stores/fetch-structure/tds/projection/QueryBuilderProjectionColumnState.js';
import { QUERY_BUILDER_TEST_ID } from '../../__lib__/QueryBuilderTesting.js';
import { QueryBuilderPanelIssueCountBadge } from '../shared/QueryBuilderPanelIssueCountBadge.js';
import { COLUMN_SORT_TYPE } from '../../graph/QueryBuilderMetaModelConst.js';
import { CAN_DROP_MAIN_GROUP_DND_TYPES } from './QueryBuilderPostFilterPanel.js';
// helpers
const createWindowColumnState = (columnState, tdsState) => {
    const operator = tdsState.windowState.operators.filter((o) => o.isColumnAggregator() &&
        o.isCompatibleWithType(columnState.getColumnType()))[0];
    const nonColoperator = guaranteeNonNullable(tdsState.windowState.operators.filter((o) => !o.isColumnAggregator())[0]);
    const columnName = operator
        ? operator.isColumnAggregator()
            ? `${operator.getLabel()} of ${columnState.columnName}`
            : columnState.columnName
        : nonColoperator.isColumnAggregator()
            ? `${nonColoperator.getLabel()} of ${columnState.columnName}`
            : columnState.columnName;
    if (operator) {
        const opState = new QueryBuilderTDS_WindowAggreationOperatorState(tdsState.windowState, operator, columnState);
        return new QueryBuilderWindowColumnState(tdsState.windowState, [], undefined, opState, columnName);
    }
    else {
        return new QueryBuilderWindowColumnState(tdsState.windowState, [columnState], undefined, new QueryBuilderTDS_WindowRankOperatorState(tdsState.windowState, nonColoperator), columnName);
    }
};
const QueryBuilderWindowColumnContextMenu = observer(forwardRef(function QueryBuilderWindowGroupByColumnContextMenu(props, ref) {
    const { columnState } = props;
    const editColumn = () => columnState.windowState.setEditColumn(columnState);
    const removeColumn = () => columnState.windowState.removeColumn(columnState);
    return (_jsxs(MenuContent, { ref: ref, children: [_jsx(MenuContentItem, { onClick: editColumn, children: "Open Editor" }), _jsx(MenuContentItem, { onClick: removeColumn, children: "Remove" })] }));
}));
const TDSColumnSelectorEditor = observer((props) => {
    const { tdsColOptions, colValue, setColumn, deleteColumn } = props;
    const applicationStore = useApplicationStore();
    const options = tdsColOptions.map((col) => ({
        label: col.columnName,
        value: col,
    }));
    const value = {
        label: colValue.columnName,
        value: colValue,
    };
    const onChange = (val) => {
        if (val !== null) {
            setColumn(val.value);
        }
    };
    const removeColumn = () => deleteColumn(colValue);
    return (_jsxs("div", { className: "panel__content__form__section__list__item query-builder__projection__options__sort", children: [_jsx(CustomSelectorInput, { className: "query-builder__projection__options__sort__dropdown", options: options, disabled: options.length < 1, onChange: onChange, value: value, darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled }), _jsx("button", { className: "query-builder__olap__tds__column__remove-btn btn--dark btn--caution", onClick: removeColumn, tabIndex: -1, title: "Remove", children: _jsx(TimesIcon, {}) })] }));
});
const QueryBuilderWindowColumnModalEditor = observer((props) => {
    // Read state
    const { windowState, windowColumnState } = props;
    const isNewWindowFunction = !windowState.windowColumns.includes(windowColumnState);
    const tdsState = windowState.tdsState;
    const applicationStore = useApplicationStore();
    // Column name
    const [selectedColumnName, setSelectedColumnName] = useState(windowColumnState.columnName);
    const changeColumnName = (event) => setSelectedColumnName(event.target.value);
    const isDuplicatedColumnName = isNewWindowFunction
        ? windowState.tdsState.tdsColumns
            .map((c) => c.columnName)
            .filter((name) => name === selectedColumnName).length > 0
        : windowState.tdsState.tdsColumns
            .map((c) => c.columnName)
            .filter((name) => name === selectedColumnName).length > 0 &&
            selectedColumnName !== windowColumnState.columnName;
    // Window operator
    const operators = windowState.operators;
    const operatorState = windowColumnState.operatorState;
    const [selectedOperatorState, setSelectedOperatorState] = useState(() => {
        if (operatorState instanceof QueryBuilderTDS_WindowAggreationOperatorState) {
            return new QueryBuilderTDS_WindowAggreationOperatorState(operatorState.windowState, operatorState.operator, operatorState.columnState);
        }
        return new QueryBuilderTDS_WindowRankOperatorState(operatorState.windowState, operatorState.operator);
    });
    const windowOperatorColumn = selectedOperatorState instanceof
        QueryBuilderTDS_WindowAggreationOperatorState
        ? selectedOperatorState.columnState
        : undefined;
    const changeWindowOperatorColumn = (val) => {
        if (selectedOperatorState instanceof
            QueryBuilderTDS_WindowAggreationOperatorState &&
            val !== null) {
            const newOpertorState = clone(selectedOperatorState);
            const newColumnName = newOpertorState.operator.isColumnAggregator()
                ? `${newOpertorState.operator.getLabel()} of ${val.value.columnName}`
                : val.value.columnName;
            newOpertorState.setColumnState(val.value);
            setSelectedOperatorState(newOpertorState);
            setSelectedColumnName(newColumnName);
        }
    };
    const changeOperator = (newOperator) => () => {
        const stateAndName = windowColumnState.getChangeOperatorStateAndColumnName(selectedOperatorState.operator, windowOperatorColumn, newOperator);
        if (stateAndName) {
            setSelectedOperatorState(stateAndName.operatorState);
            setSelectedColumnName(stateAndName.columnName);
        }
    };
    const allColumns = isNewWindowFunction
        ? tdsState.tdsColumns
        : windowColumnState.possibleReferencedColumns;
    const allColumnsOptions = allColumns.map((w) => ({
        label: w.columnName,
        value: w,
    }));
    // Window columns
    const [selectedWindowColumns, setSelectedWindowColumns] = useState([
        ...windowColumnState.windowColumns,
    ]);
    const availableColumns = allColumns.filter((e) => !selectedWindowColumns.includes(e));
    const addWindowColumn = () => {
        if (availableColumns.length > 0) {
            setSelectedWindowColumns([
                ...selectedWindowColumns,
                guaranteeNonNullable(availableColumns[0]),
            ]);
        }
    };
    const updateWindowColumn = (idx, column) => {
        const newWindowColumns = clone(selectedWindowColumns);
        newWindowColumns[idx] = column;
        setSelectedWindowColumns(newWindowColumns);
    };
    const deleteWindowColumn = (column) => {
        const newWindowColumns = clone(selectedWindowColumns);
        deleteEntry(newWindowColumns, column);
        setSelectedWindowColumns(newWindowColumns);
    };
    // Sort by
    const [selectedSortBy, setSelectedSortBy] = useState(() => {
        const sortBy = windowColumnState.sortByState;
        if (sortBy) {
            return new WindowGroupByColumnSortByState(sortBy.columnState, sortBy.sortType);
        }
        return undefined;
    });
    const changeSortBy = (sortOp) => () => {
        if (selectedSortBy?.sortType !== sortOp) {
            if (sortOp) {
                const newSortByState = new WindowGroupByColumnSortByState(selectedSortBy?.columnState
                    ? selectedSortBy.columnState
                    : guaranteeNonNullable(windowColumnState.possibleReferencedColumns[0]), sortOp);
                setSelectedSortBy(newSortByState);
            }
            else {
                setSelectedSortBy(undefined);
            }
        }
    };
    const changeSortCol = (val) => {
        if (selectedSortBy && val !== null) {
            const newSortByState = new WindowGroupByColumnSortByState(val.value, selectedSortBy.sortType);
            setSelectedSortBy(newSortByState);
        }
    };
    // Modal lifecycle actions
    const handleCancel = () => {
        windowState.setEditColumn(undefined);
    };
    const handleApply = () => {
        windowColumnState.setColumnName(selectedColumnName);
        windowColumnState.setOperatorState(selectedOperatorState);
        windowColumnState.setWindows(selectedWindowColumns);
        windowColumnState.setSortBy(selectedSortBy);
        windowState.addWindowColumn(windowColumnState);
        handleCancel();
    };
    return (_jsx(Dialog, { open: Boolean(windowState.editColumn), onClose: handleCancel, classes: {
            root: 'editor-modal__root-container',
            container: 'editor-modal__container',
            paper: 'editor-modal__content',
        }, children: _jsxs(Modal, { darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled, className: clsx([
                'query-builder__olap__modal',
                {
                    'query-editor--light': applicationStore.layoutService
                        .TEMPORARY__isLightColorThemeEnabled,
                },
            ]), children: [_jsx(ModalHeader, { title: isNewWindowFunction
                        ? 'Create Window Function Column'
                        : 'Update Window Function Column' }), _jsxs("div", { className: "query-builder__olap__modal__body", children: [_jsxs(PanelFormSection, { children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Window Operator" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Window aggregation function to apply and column if required by function" }), _jsx("div", { className: "panel__content__form__section__list", children: _jsx("div", { className: "panel__content__form__section__list__items", children: _jsxs("div", { className: "query-builder__olap__column__operation__operator", children: [windowOperatorColumn && (_jsx("div", { className: "panel__content__form__section__list__item query-builder__olap__tds__column__options", children: _jsx(CustomSelectorInput, { className: "query-builder__olap__tds__column__dropdown", options: allColumnsOptions, disabled: allColumnsOptions.length < 1, onChange: changeWindowOperatorColumn, value: {
                                                            value: windowOperatorColumn,
                                                            label: windowOperatorColumn.columnName,
                                                        }, darkMode: !applicationStore.layoutService
                                                            .TEMPORARY__isLightColorThemeEnabled }) })), _jsx("div", { className: clsx('query-builder__olap__column__operation__operator__label', {
                                                        'query-builder__olap__column__operation__operator__label__agg': !windowOperatorColumn,
                                                    }), children: selectedOperatorState.operator.getLabel() }), _jsxs(ControlledDropdownMenu, { className: "query-builder__olap__column__operation__operator__dropdown", title: "Choose Window Function Operator...", disabled: !operators.length, content: _jsx(MenuContent, { children: operators.map((op) => (_jsx(MenuContentItem, { className: "query-builder__olap__column__operation__operator__dropdown__option", onClick: changeOperator(op), children: op.getLabel() }, op.uuid))) }), menuProps: {
                                                        anchorOrigin: {
                                                            vertical: 'bottom',
                                                            horizontal: 'left',
                                                        },
                                                        transformOrigin: {
                                                            vertical: 'top',
                                                            horizontal: 'left',
                                                        },
                                                        elevation: 7,
                                                    }, children: [_jsx("div", { className: "query-builder__olap__column__operation__operator__badge", children: _jsx(SigmaIcon, {}) }), _jsx("div", { className: "query-builder__olap__column__operation__operator__dropdown__trigger", children: _jsx(CaretDownIcon, {}) })] })] }) }) })] }), _jsxs(PanelFormSection, { children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Window Columns" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Represents the window of columns that will partition the rows for which to apply the aggregate function" }), _jsxs("div", { className: "panel__content__form__section__list", children: [_jsx("div", { className: "panel__content__form__section__list__items", children: selectedWindowColumns.map((value, idx) => (_jsx(TDSColumnSelectorEditor, { colValue: value, setColumn: (v) => updateWindowColumn(idx, v), deleteColumn: (v) => deleteWindowColumn(v), tdsColOptions: availableColumns }, value.uuid))) }), _jsx("div", { className: "panel__content__form__section__list__new-item__add", children: _jsx("button", { className: "panel__content__form__section__list__new-item__add-btn btn btn--dark", disabled: !availableColumns.length, onClick: addWindowColumn, tabIndex: -1, children: "Add Value" }) })] })] }), _jsxs(PanelFormSection, { children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Sort By" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Orders by the designated column" }), _jsx("div", { className: "panel__content__form__section__header__prompt" }), _jsx("div", { className: "panel__content__form__section__list", children: _jsxs("div", { className: "query-builder__olap__column__sortby__operator", children: [selectedSortBy && (_jsx("div", { className: "panel__content__form__section__list__item query-builder__olap__tds__column__options", children: _jsx(CustomSelectorInput, { className: "query-builder__olap__tds__column__dropdown", options: allColumnsOptions, disabled: allColumnsOptions.length < 1, onChange: changeSortCol, value: {
                                                        value: selectedSortBy.columnState,
                                                        label: selectedSortBy.columnState.columnName,
                                                    }, darkMode: !applicationStore.layoutService
                                                        .TEMPORARY__isLightColorThemeEnabled }) })), !selectedSortBy && (_jsx("div", { className: "query-builder__olap__column__sortby__none", children: "(none)" })), selectedSortBy && (_jsx("div", { className: "query-builder__olap__column__sortby__operator__label", children: selectedSortBy.sortType.toLowerCase() })), _jsxs(ControlledDropdownMenu, { className: "query-builder__olap__column__sortby__operator__dropdown", title: "Choose Window Function SortBy Operator...", content: _jsxs(MenuContent, { children: [_jsx(MenuContentItem, { className: "query-builder__olap__column__sortby__operator__dropdown__option", onClick: changeSortBy(undefined), children: "(none)" }, "none"), Object.values(COLUMN_SORT_TYPE).map((op) => (_jsx(MenuContentItem, { className: "query-builder__olap__column__sortby__operator__dropdown__option", onClick: changeSortBy(op), children: op.toLowerCase() }, op)))] }), menuProps: {
                                                    anchorOrigin: { vertical: 'bottom', horizontal: 'left' },
                                                    transformOrigin: { vertical: 'top', horizontal: 'left' },
                                                    elevation: 7,
                                                }, children: [_jsx("div", { className: clsx('query-builder__olap__column__sortby__operator__badge', {
                                                            'query-builder__olap__column__sortby__operator__badge--activated': Boolean(selectedSortBy),
                                                        }), tabIndex: -1, children: _jsx(SortIcon, {}) }), _jsx("div", { className: "query-builder__olap__column__sortby__operator__dropdown__trigger", tabIndex: -1, children: _jsx(CaretDownIcon, {}) })] })] }) })] }), _jsxs(PanelFormSection, { children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Window Function Column Name" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Name of Window Function Column that will be part of TDS Result" }), _jsx(InputWithInlineValidation, { className: "query-builder__olap__column__name__input input-group__input", spellCheck: false, value: selectedColumnName, onChange: changeColumnName, error: isDuplicatedColumnName ? 'Duplicated column' : undefined })] })] }), _jsxs(ModalFooter, { children: [_jsx(ModalFooterButton, { text: isNewWindowFunction ? 'Create' : 'Apply', onClick: handleApply, disabled: isDuplicatedColumnName }), _jsx(ModalFooterButton, { text: "Cancel", onClick: handleCancel, type: "secondary" })] })] }) }));
});
const TDSColumnReferenceEditor = observer((props) => {
    const { handleChange, tdsColumn, selectionEditor } = props;
    const applicationStore = useApplicationStore();
    const [opAnchor, setOpAnchor] = useState(null);
    const openOpAnchor = (event) => {
        if (selectionEditor) {
            setOpAnchor(event.currentTarget);
        }
    };
    const closeOpAnchor = () => {
        setOpAnchor(null);
    };
    const value = {
        label: tdsColumn.columnName,
        value: tdsColumn,
    };
    const options = selectionEditor?.options.map((col) => ({
        label: col.columnName,
        value: col,
    })) ?? [];
    const onChange = (val) => {
        if (val !== null) {
            handleChange(val.value);
        }
    };
    const handleDrop = useCallback((item) => {
        handleChange(item.columnState);
    }, [handleChange]);
    const [{ isDragOver }, dropConnector] = useDrop(() => ({
        accept: [
            QUERY_BUILDER_PROJECTION_COLUMN_DND_TYPE,
            QUERY_BUILDER_WINDOW_COLUMN_DND_TYPE,
        ],
        drop: (item, monitor) => {
            if (!monitor.didDrop()) {
                handleDrop(item);
            }
        },
        collect: (monitor) => ({
            isDragOver: monitor.isOver({ shallow: true }),
        }),
    }), [handleDrop]);
    const ref = useRef(null);
    dropConnector(ref);
    return (_jsxs(_Fragment, { children: [_jsx("button", { onClick: openOpAnchor, className: "query-builder__olap__tds__column", children: _jsx("div", { ref: ref, className: "query-builder__olap__tds__column-badge", children: _jsx(PanelEntryDropZonePlaceholder, { isDragOver: isDragOver, label: "Change Column", children: _jsx("div", { className: "query-builder__olap__tds__column-badge__content", children: _jsx("div", { className: "query-builder__olap__tds__column-badge__property", title: `${tdsColumn.columnName}`, children: tdsColumn.columnName }) }) }) }) }), selectionEditor && (_jsx(BasePopover, { open: Boolean(opAnchor), anchorEl: opAnchor, onClose: closeOpAnchor, anchorOrigin: {
                    vertical: 'bottom',
                    horizontal: 'center',
                }, transformOrigin: {
                    vertical: 'top',
                    horizontal: 'center',
                }, children: _jsx("div", { className: "query-builder__olap__column__window__popover", children: _jsx("div", { className: "panel__content__form__section__list__item query-builder__olap__tds__column__options", children: _jsx(CustomSelectorInput, { className: "query-builder__projection__options__sort__dropdown", options: options, disabled: options.length < 1, onChange: onChange, value: value, darkMode: !applicationStore.layoutService
                                .TEMPORARY__isLightColorThemeEnabled }) }) }) }))] }));
});
const QueryBuilderWindowColumnEditor = observer((props) => {
    const { windowColumnState } = props;
    const windowState = windowColumnState.windowState;
    const tdsState = windowState.tdsState;
    const operators = windowState.operators;
    // state
    const ref = useRef(null);
    const handleRef = useRef(null);
    const [windowAnchor, setWindowAnchor] = useState(null);
    const openWindowPopover = (event) => {
        setWindowAnchor(event.currentTarget);
    };
    const closeWindowPopover = () => {
        setWindowAnchor(null);
    };
    const [isSelectedFromContextMenu, setIsSelectedFromContextMenu] = useState(false);
    const onContextMenuOpen = () => setIsSelectedFromContextMenu(true);
    const onContextMenuClose = () => setIsSelectedFromContextMenu(false);
    // column Name
    const changeColumnName = (event) => windowColumnState.setColumnName(event.target.value);
    const isDuplicatedColumnName = tdsState.isDuplicateColumn(windowColumnState);
    const isInvalidColumnName = windowState.invalidWindowColumnNames.some((col) => col.invalidColumnName === windowColumnState.columnName ||
        col.missingColumnName === windowColumnState.columnName);
    // window columns
    const windowOptions = windowColumnState.possibleReferencedColumns;
    const addWindowOptions = windowOptions.filter((e) => !windowColumnState.windowColumns.includes(e));
    const addWindowValue = () => {
        if (addWindowOptions.length > 0) {
            windowColumnState.addWindow(guaranteeNonNullable(addWindowOptions[0]));
        }
    };
    // operator
    const operationState = windowColumnState.operatorState;
    const aggregateColumn = operationState instanceof QueryBuilderTDS_WindowAggreationOperatorState
        ? operationState.columnState
        : undefined;
    const changeOperator = (olapOp) => () => {
        windowColumnState.changeOperator(olapOp);
    };
    // sortby
    const sortByState = windowColumnState.sortByState;
    const changeSortBy = (sortOp) => () => {
        windowColumnState.changeSortBy(sortOp);
    };
    // action
    const isRemovalDisabled = windowState.tdsState.isColumnInUse(windowColumnState);
    const removeColumn = () => {
        windowColumnState.windowState.removeColumn(windowColumnState);
    };
    const editoColumn = () => {
        windowState.setEditColumn(windowColumnState);
    };
    // Drag and Drop
    const handleHover = useCallback((item, monitor) => {
        const dragIndex = tdsState.windowState.windowColumns.findIndex((e) => e === item.columnState);
        const hoverIndex = tdsState.windowState.windowColumns.findIndex((e) => e === windowColumnState);
        if (dragIndex === -1 || hoverIndex === -1 || dragIndex === hoverIndex) {
            return;
        }
        // move the item being hovered on when the dragged item position is beyond the its middle point
        const hoverBoundingReact = ref.current?.getBoundingClientRect();
        const distanceThreshold = ((hoverBoundingReact?.bottom ?? 0) - (hoverBoundingReact?.top ?? 0)) /
            2;
        const dragDistance = (monitor.getClientOffset()?.y ?? 0) - (hoverBoundingReact?.top ?? 0);
        if (dragIndex < hoverIndex && dragDistance < distanceThreshold) {
            return;
        }
        if (dragIndex > hoverIndex && dragDistance > distanceThreshold) {
            return;
        }
        windowState.moveColumn(dragIndex, hoverIndex);
    }, [windowColumnState, windowState, tdsState.windowState.windowColumns]);
    const [, dropConnector] = useDrop(() => ({
        accept: [QUERY_BUILDER_WINDOW_COLUMN_DND_TYPE],
        hover: (item, monitor) => handleHover(item, monitor),
    }), [handleHover]);
    const [{ olapColumnBeingDragged }, dragConnector, dragPreviewConnector] = useDrag(() => ({
        type: QUERY_BUILDER_WINDOW_COLUMN_DND_TYPE,
        item: () => ({
            columnState: windowColumnState,
        }),
        collect: (monitor) => ({
            /**
             * @workaround typings - https://github.com/react-dnd/react-dnd/pull/3484
             */
            olapColumnBeingDragged: 
            // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
            monitor.getItem()
                ?.columnState,
        }),
    }), [windowColumnState]);
    const isBeingDragged = windowColumnState === olapColumnBeingDragged;
    dragConnector(handleRef);
    dropConnector(ref);
    useDragPreviewLayer(dragPreviewConnector);
    const handleOpDrop = (val) => {
        if (operationState instanceof QueryBuilderTDS_WindowAggreationOperatorState) {
            operationState.setColumnState(val);
        }
    };
    const handleSortDrop = (val) => {
        if (sortByState) {
            sortByState.setColumnState(val);
        }
    };
    const handleWindowDrop = useCallback((item) => {
        const colState = item.columnState;
        if (windowColumnState.possibleReferencedColumns.includes(colState) &&
            !windowColumnState.windowColumns.includes(colState)) {
            windowColumnState.addWindow(colState);
        }
    }, [windowColumnState]);
    const [{ isDragOver }, operationDropConnector] = useDrop(() => ({
        accept: [
            QUERY_BUILDER_PROJECTION_COLUMN_DND_TYPE,
            QUERY_BUILDER_WINDOW_COLUMN_DND_TYPE,
        ],
        drop: (item, monitor) => {
            if (!monitor.didDrop()) {
                handleWindowDrop(item);
            }
        },
        collect: (monitor) => ({
            isDragOver: monitor.isOver({ shallow: true }),
        }),
    }), [handleWindowDrop]);
    const opRef = useRef(null);
    operationDropConnector(opRef);
    return (_jsx(PanelDnDEntry, { ref: ref, className: "query-builder__olap__column", showPlaceholder: isBeingDragged, placeholder: _jsx("div", { className: "query-builder__olap__column__placeholder" }), placeholderContainerClassName: "query-builder__olap__column__placeholder__container", children: _jsxs(ContextMenu, { content: _jsx(QueryBuilderWindowColumnContextMenu, { columnState: windowColumnState }), className: clsx('query-builder__olap__column__context-menu', {
                'query-builder__olap__column--selected-from-context-menu': isSelectedFromContextMenu,
            }), menuProps: { elevation: 7 }, onOpen: onContextMenuOpen, onClose: onContextMenuClose, children: [_jsx(PanelEntryDragHandle, { isDragging: isBeingDragged, className: "query-builder__olap__column__drag-handle__container", dragSourceConnector: handleRef }), _jsx("div", { className: "query-builder__olap__column__operation", children: _jsxs("div", { className: "query-builder__olap__column__operation__operator", children: [aggregateColumn && (_jsx(TDSColumnReferenceEditor, { tdsColumn: aggregateColumn, handleChange: handleOpDrop, selectionEditor: {
                                    options: windowColumnState.possibleReferencedColumns,
                                } })), _jsx("div", { className: clsx('query-builder__olap__column__operation__operator__label', {
                                    'query-builder__olap__column__operation__operator__label__agg': !aggregateColumn,
                                }), children: operationState.operator.getLabel() }), _jsxs(ControlledDropdownMenu, { className: "query-builder__olap__column__operation__operator__dropdown", disabled: !operators.length, title: "Choose Window Function Operator...", content: _jsx(MenuContent, { children: operators.map((op) => (_jsx(MenuContentItem, { className: "query-builder__olap__column__operation__operator__dropdown__option", onClick: changeOperator(op), children: op.getLabel() }, op.uuid))) }), menuProps: {
                                    anchorOrigin: { vertical: 'bottom', horizontal: 'left' },
                                    transformOrigin: { vertical: 'top', horizontal: 'left' },
                                    elevation: 7,
                                }, children: [_jsx("div", { className: "query-builder__olap__column__operation__operator__badge", children: _jsx(SigmaIcon, {}) }), _jsx("div", { className: "query-builder__olap__column__operation__operator__dropdown__trigger", children: _jsx(CaretDownIcon, {}) })] })] }) }), _jsxs("div", { className: "query-builder__olap__column__window", children: [_jsx("button", { ref: opRef, title: "Click to edit or drag and drop columns", onClick: openWindowPopover, className: "query-builder__olap__column__window__content", children: _jsxs(PanelEntryDropZonePlaceholder, { isDragOver: isDragOver, label: "Add", children: [_jsxs("div", { title: `${windowColumnState.windowColumns.length} columns partitioned`, className: "query-builder__olap__column__window__content__label", children: ["(", windowColumnState.windowColumns.length, ")"] }), _jsx("div", { className: clsx('query-builder__olap__column__window__operator__badge'), tabIndex: -1, title: "Edit window columns...", children: _jsx(WindowIcon, {}) })] }) }), _jsx(BasePopover, { open: Boolean(windowAnchor), anchorEl: windowAnchor, onClose: closeWindowPopover, anchorOrigin: {
                                vertical: 'bottom',
                                horizontal: 'center',
                            }, transformOrigin: {
                                vertical: 'top',
                                horizontal: 'center',
                            }, children: _jsx("div", { className: "query-builder__olap__column__window__popover", children: _jsxs("div", { className: "panel__content__form__section__list", children: [_jsx("div", { className: "panel__content__form__section__list__items", children: windowColumnState.windowColumns.map((value, idx) => (_jsx(TDSColumnSelectorEditor, { colValue: value, setColumn: (v) => windowColumnState.changeWindow(v, idx), deleteColumn: (v) => windowColumnState.deleteWindow(v), tdsColOptions: addWindowOptions }, value.uuid))) }), _jsx("div", { className: "panel__content__form__section__list__new-item__add", children: _jsx("button", { className: "panel__content__form__section__list__new-item__add-btn btn btn--dark", disabled: !addWindowOptions.length, onClick: addWindowValue, tabIndex: -1, children: "Add Value" }) })] }) }) })] }), _jsx("div", { className: "query-builder__olap__column__sortby", children: _jsxs("div", { className: "query-builder__olap__column__sortby__operator", children: [sortByState && (_jsx(TDSColumnReferenceEditor, { tdsColumn: sortByState.columnState, handleChange: handleSortDrop, selectionEditor: {
                                    options: windowColumnState.possibleReferencedColumns,
                                } })), !sortByState && (_jsx("div", { className: "query-builder__olap__column__sortby__none", children: "(none)" })), sortByState && (_jsx("div", { className: "query-builder__olap__column__sortby__operator__label", children: sortByState.sortType.toLowerCase() })), _jsxs(ControlledDropdownMenu, { className: "query-builder__olap__column__sortby__operator__dropdown", title: "Choose Window Function SortBy Operator...", content: _jsxs(MenuContent, { children: [_jsx(MenuContentItem, { className: "query-builder__olap__column__sortby__operator__dropdown__option", onClick: changeSortBy(undefined), children: "(none)" }, "none"), Object.values(COLUMN_SORT_TYPE).map((op) => (_jsx(MenuContentItem, { className: "query-builder__olap__column__sortby__operator__dropdown__option", onClick: changeSortBy(op), children: op.toLowerCase() }, op)))] }), menuProps: {
                                    anchorOrigin: { vertical: 'bottom', horizontal: 'left' },
                                    transformOrigin: { vertical: 'top', horizontal: 'left' },
                                    elevation: 7,
                                }, children: [_jsx("div", { className: clsx('query-builder__olap__column__sortby__operator__badge', {
                                            'query-builder__olap__column__sortby__operator__badge--activated': Boolean(sortByState),
                                        }), children: _jsx(SortIcon, {}) }), _jsx("div", { className: "query-builder__olap__column__sortby__operator__dropdown__trigger", children: _jsx(CaretDownIcon, {}) })] })] }) }), _jsx("div", { className: "query-builder__olap__column__name", children: _jsx(InputWithInlineValidation, { className: "query-builder__olap__column__name__input input-group__input", spellCheck: false, value: windowColumnState.columnName, onChange: changeColumnName, error: isDuplicatedColumnName
                            ? 'Duplicated column'
                            : isInvalidColumnName
                                ? 'Invalid column order'
                                : undefined }) }), _jsxs("div", { className: "query-builder__olap__column__actions", children: [_jsx("button", { className: "query-builder__olap__column__action", tabIndex: -1, onClick: editoColumn, children: _jsx(EditIcon, {}) }), _jsx("button", { className: "query-builder__olap__column__action", tabIndex: -1, onClick: removeColumn, disabled: isRemovalDisabled, title: isRemovalDisabled
                                ? "This column is used in the post filter and can't be removed"
                                : 'Remove', children: _jsx(TimesIcon, {}) })] })] }) }));
});
export const QueryBuilderTDSWindowPanel = observer((props) => {
    const { tdsWindowState } = props;
    const applicationStore = useApplicationStore();
    const createTDSWindow = () => {
        const col = tdsWindowState.tdsState.tdsColumns[0];
        if (col) {
            const newWindowState = createWindowColumnState(col, tdsWindowState.tdsState);
            tdsWindowState.setEditColumn(newWindowState);
        }
    };
    // Drag and Drop
    const handleDrop = useCallback(async (item) => {
        try {
            const newWindowState = createWindowColumnState(item.columnState, tdsWindowState.tdsState);
            tdsWindowState.addWindowColumn(newWindowState);
        }
        catch (error) {
            assertErrorThrown(error);
            applicationStore.notificationService.notifyError(error.message);
            return;
        }
    }, [applicationStore, tdsWindowState]);
    const [{ isDragOver }, dropConnector] = useDrop(() => ({
        accept: [
            QUERY_BUILDER_PROJECTION_COLUMN_DND_TYPE,
            QUERY_BUILDER_WINDOW_COLUMN_DND_TYPE,
        ],
        drop: (item, monitor) => {
            if (!monitor.didDrop()) {
                handleDrop(item).catch(applicationStore.alertUnhandledError);
            } // prevent drop event propagation to accomondate for nested DnD
        },
        collect: (monitor) => ({
            isDragOver: monitor.isOver({ shallow: true }),
        }),
    }), [applicationStore, handleDrop]);
    const { isDroppable } = useDragLayer((monitor) => ({
        isDroppable: monitor.isDragging() &&
            CAN_DROP_MAIN_GROUP_DND_TYPES.includes(monitor.getItemType()?.toString() ?? ''),
    }));
    const ref = useRef(null);
    dropConnector(ref);
    return (_jsx(Panel, { children: _jsxs("div", { "data-testid": QUERY_BUILDER_TEST_ID.QUERY_BUILDER_WINDOW_GROUPBY, className: "panel", children: [_jsxs(PanelHeader, { children: [_jsxs("div", { className: "panel__header__title", children: [_jsx("div", { className: "panel__header__title__label", children: "window function" }), tdsWindowState.windowValidationIssues.length > 0 && (_jsx(QueryBuilderPanelIssueCountBadge, { issues: tdsWindowState.windowValidationIssues }))] }), _jsx(PanelHeaderActions, { children: _jsx(PanelHeaderActionItem, { onClick: createTDSWindow, disabled: !tdsWindowState.tdsState.tdsColumns.length, title: "Create Window Function Column", children: _jsx(PlusIcon, {}) }) })] }), _jsx(PanelContent, { children: _jsxs(PanelDropZone, { isDragOver: isDragOver && tdsWindowState.isEmpty, isDroppable: isDroppable && tdsWindowState.isEmpty, dropTargetConnector: dropConnector, children: [tdsWindowState.isEmpty && (_jsx(BlankPanelPlaceholder, { text: "Add Window Function Column", tooltipText: "Drag and drop columns here" })), !tdsWindowState.isEmpty && (_jsxs(_Fragment, { children: [_jsx(DragPreviewLayer, { labelGetter: (item) => item.columnState.columnName === ''
                                            ? '(unknown)'
                                            : item.columnState.columnName, types: [QUERY_BUILDER_WINDOW_COLUMN_DND_TYPE] }), _jsx("div", { "data-testid": QUERY_BUILDER_TEST_ID.QUERY_BUILDER_TDS, className: "query-builder__olap__columns", children: tdsWindowState.windowColumns.map((col) => (_jsx(QueryBuilderWindowColumnEditor, { windowColumnState: col }, col.uuid))) })] })), isDroppable && !tdsWindowState.isEmpty && (_jsx("div", { ref: ref, className: "query-builder__olap__free-drop-zone__container", children: _jsx(PanelEntryDropZonePlaceholder, { isDragOver: isDragOver, isDroppable: isDroppable, className: "query-builder__olap__free-drop-zone", label: "Add new window function column", children: _jsx(_Fragment, {}) }) }))] }) }), tdsWindowState.editColumn && (_jsx(QueryBuilderWindowColumnModalEditor, { windowState: tdsWindowState, windowColumnState: tdsWindowState.editColumn }))] }) }));
});
//# sourceMappingURL=QueryBuilderTDSWindowPanel.js.map