"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GridFilterExpressionEditor = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_redux_1 = require("react-redux");
const rebass_1 = require("rebass");
const ExpressionEditor_1 = require("../../components/ExpressionEditor");
const NamedQueryContext_1 = require("../../components/ExpressionEditor/NamedQueryContext");
const SimpleButton_1 = tslib_1.__importDefault(require("../../components/SimpleButton"));
const NamedQueryRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/NamedQueryRedux"));
const PopupRedux_1 = require("../../Redux/ActionsReducers/PopupRedux");
const ModuleConstants_1 = require("../../Utilities/Constants/ModuleConstants");
const StringExtensions_1 = require("../../Utilities/Extensions/StringExtensions");
const Helper_1 = tslib_1.__importDefault(require("../../Utilities/Helpers/Helper"));
const AdaptableContext_1 = require("../AdaptableContext");
const useGridFilterOptionsForExpressionEditor_1 = require("./useGridFilterOptionsForExpressionEditor");
const GridFilterExpressionEditor = (props) => {
    const dispatch = (0, react_redux_1.useDispatch)();
    const { api } = (0, AdaptableContext_1.useAdaptable)();
    const [namedQuery, setNamedQuery] = React.useState(null);
    const [expression, setExpression] = React.useState(props.expression);
    const isExpressionValid = api.internalApi
        .getQueryLanguageService()
        .validateBoolean(expression, ModuleConstants_1.GridFilterModuleId).isValid;
    const isExistingNamedQuery = Helper_1.default.objectExists(api.namedQueryApi.getNamedQueries().find((q) => q.BooleanExpression == expression));
    const initialData = React.useMemo(() => api.internalApi.getQueryPreviewData(), []);
    const namedQueryValidationError = namedQuery
        ? api.namedQueryApi.isValidNamedQuery(namedQuery).message
        : '';
    const hasNamedQueryError = (0, StringExtensions_1.IsNotNullOrEmpty)(namedQueryValidationError);
    const onRunQuery = (expression) => {
        api.filterApi.gridFilterApi.setGridFilterExpression(expression);
    };
    const onAddNamedQuery = (namedQuery) => dispatch(NamedQueryRedux.NamedQueryAdd(namedQuery));
    const handleSaveQuery = () => {
        dispatch((0, PopupRedux_1.PopupShowForm)({
            Id: 'save_query_form',
            Form: {
                title: 'Save as Named Query',
                fields: [
                    {
                        name: 'name',
                        label: 'Name',
                        fieldType: 'text',
                    },
                ],
                buttons: [
                    {
                        label: 'Cancel',
                        buttonStyle: {
                            variant: 'text',
                            tone: 'none',
                        },
                    },
                    {
                        label: 'Save',
                        buttonStyle: {
                            variant: 'raised',
                            tone: 'accent',
                        },
                        disabled: (button, context) => {
                            if (context.formData.name === '') {
                                return true;
                            }
                            const testQuery = {
                                Name: context.formData.name,
                                BooleanExpression: expression,
                            };
                            const namedQueryValidationResult = api.namedQueryApi.isValidNamedQuery(testQuery);
                            if (!namedQueryValidationResult.valid) {
                                return true;
                            }
                        },
                        onClick: (button, context) => {
                            onAddNamedQuery({
                                Name: context.formData.name,
                                BooleanExpression: expression,
                            });
                        },
                    },
                ],
            },
        }));
    };
    const expressionEditorProps = (0, useGridFilterOptionsForExpressionEditor_1.useGridFilterOptionsForExpressionEditorProps)();
    const actionsDisabled = !isExpressionValid || (0, StringExtensions_1.IsNullOrEmpty)(expression) || hasNamedQueryError || isExistingNamedQuery;
    return (React.createElement(NamedQueryContext_1.NamedQueryContext.Provider, { value: {
            namedQuery: namedQuery,
            setNamedQuery: (newQuery) => {
                setNamedQuery(newQuery);
            },
        } },
        React.createElement(rebass_1.Flex, { height: "100%", flexDirection: "column" },
            React.createElement(ExpressionEditor_1.ExpressionEditor, { ...expressionEditorProps, type: 'boolean', module: ModuleConstants_1.GridFilterModuleId, value: expression, onChange: (expression) => setExpression(expression), initialData: initialData, columns: api.columnApi.internalApi.getQueryableColumnsForUIEditor(), fields: api.expressionApi.internalApi.getAvailableFields(), namedQueries: api.namedQueryApi.getNamedQueries(), api: api }),
            React.createElement(rebass_1.Flex, { flexDirection: "row", padding: 1, alignItems: "center" },
                props.onDismiss && (React.createElement(SimpleButton_1.default, { margin: 1, variant: "text", "data-name": "action-close", onClick: () => {
                        props.onDismiss();
                    } }, "CLOSE")),
                React.createElement(rebass_1.Box, { flex: 1 }),
                React.createElement(SimpleButton_1.default, { disabled: actionsDisabled, onClick: handleSaveQuery, icon: "save" }, "Save Query"),
                React.createElement(SimpleButton_1.default, { variant: "raised", tone: "accent", "data-name": "action-run", margin: 1, icon: "play", onClick: () => {
                        if (namedQuery) {
                            onAddNamedQuery({
                                Name: namedQuery.Name,
                                BooleanExpression: expression,
                            });
                        }
                        onRunQuery(expression);
                        props?.onDismiss?.();
                    }, disabled: actionsDisabled }, "Apply Grid Filter")))));
};
exports.GridFilterExpressionEditor = GridFilterExpressionEditor;
