"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useGridFilterExpressionEditor = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_redux_1 = require("react-redux");
const SystemRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/SystemRedux"));
const ModuleConstants_1 = require("../../Utilities/Constants/ModuleConstants");
const StringExtensions_1 = tslib_1.__importDefault(require("../../Utilities/Extensions/StringExtensions"));
const AdaptableContext_1 = require("../AdaptableContext");
const PopupRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/PopupRedux"));
const useGridFilterExpressionEditor = () => {
    var _a, _b, _c;
    const adaptable = (0, AdaptableContext_1.useAdaptable)();
    const dispatch = (0, react_redux_1.useDispatch)();
    const currentLayout = (0, react_redux_1.useSelector)((state) => {
        return state.Layout.Layouts.find((l) => l.Name == state.Layout.CurrentLayout);
    });
    const isReadOnly = Boolean(currentLayout === null || currentLayout === void 0 ? void 0 : currentLayout.IsReadOnly);
    const gridFilter = currentLayout === null || currentLayout === void 0 ? void 0 : currentLayout.GridFilter;
    const [isAdaptableReady, setIsAdaptableReady] = React.useState(false);
    const [expression, setExpression] = React.useState(() => {
        return adaptable.api.gridFilterApi.getCurrentGridFilterExpression();
    });
    const namedQueries = (_a = (0, react_redux_1.useSelector)((state) => state.NamedQuery.NamedQueries)) !== null && _a !== void 0 ? _a : [];
    const cachedQueries = (_b = (0, react_redux_1.useSelector)((state) => state.System.CachedQueries)) !== null && _b !== void 0 ? _b : [];
    const isSuspended = (_c = gridFilter === null || gridFilter === void 0 ? void 0 : gridFilter.IsSuspended) !== null && _c !== void 0 ? _c : false;
    const onAddCachedQuery = (cachedQuery) => {
        dispatch(SystemRedux.SystemCachedQueryAdd(cachedQuery));
    };
    const gridFilterHelpPage = adaptable.ModuleService.getModuleById('GridFilter').moduleInfo.HelpPage;
    const gridFilterLinkDisabled = !adaptable.api.internalApi.isDocumentationLinksDisplayed();
    React.useEffect(() => {
        adaptable.api.eventApi.on('AdaptableReady', () => {
            setIsAdaptableReady(true);
        });
    }, []);
    React.useEffect(() => {
        var _a;
        if ((gridFilter === null || gridFilter === void 0 ? void 0 : gridFilter.Expression) != expression) {
            setExpression((_a = gridFilter === null || gridFilter === void 0 ? void 0 : gridFilter.Expression) !== null && _a !== void 0 ? _a : '');
        }
    }, [gridFilter === null || gridFilter === void 0 ? void 0 : gridFilter.Expression]);
    const isExpressionValid = expression == '' ||
        adaptable.api.internalApi
            .getQueryLanguageService()
            .validateBoolean(expression, ModuleConstants_1.NamedQueryModuleId).isValid;
    const isExpressionNamedQuery = namedQueries.find((sq) => sq.BooleanExpression == expression) != null;
    let availableColumns = adaptable.api.columnApi.getColumns().map((col) => {
        return {
            label: col.friendlyName,
            onClick: () => {
                // Bogdan - im sure there is a better way to do this check with fancy operators i dont know
                const newExp = StringExtensions_1.default.IsNotNullOrEmpty(expression) ? expression : '';
                setExpression(newExp + `[${col.columnId}]`);
            },
        };
    });
    const clearQuery = () => {
        adaptable.api.gridFilterApi.clearGridFilter();
        setExpression('');
    };
    const runQuery = (newExpression = expression) => {
        if (StringExtensions_1.default.IsNullOrEmpty(newExpression) &&
            StringExtensions_1.default.IsNotNullOrEmpty(gridFilter === null || gridFilter === void 0 ? void 0 : gridFilter.Expression)) {
            // user pressed enter key with an empty input => clear existing expression
            adaptable.api.gridFilterApi.setGridFilterExpression('');
            return;
        }
        if (!adaptable.api.internalApi
            .getQueryLanguageService()
            .validateBoolean(newExpression, ModuleConstants_1.NamedQueryModuleId).isValid) {
            return;
        }
        if (StringExtensions_1.default.IsNotNullOrEmpty(expression)) {
            let cachedQuery = {
                expression: expression,
                time: new Date(),
            };
            if (cachedQuery) {
                onAddCachedQuery(cachedQuery);
            }
        }
        adaptable.api.gridFilterApi.setGridFilterExpression(newExpression);
    };
    const gridFilterAccessLevel = React.useMemo(() => {
        return adaptable.api.entitlementApi.getEntitlementAccessLevelForModule(ModuleConstants_1.GridFilterModuleId);
    }, []);
    const namedQueryModuleAccessLevel = adaptable.api.entitlementApi.getEntitlementAccessLevelForModule(ModuleConstants_1.NamedQueryModuleId);
    const onShowNamedQueries = (value, popup) => dispatch(PopupRedux.PopupShowScreen(ModuleConstants_1.NamedQueryModuleId, popup, {
        action: 'New',
        source: 'Other',
        value,
    }));
    const saveQuery = () => {
        const namedqueryPopuName = adaptable.api.internalApi
            .getModuleService()
            .getModuleById(ModuleConstants_1.NamedQueryModuleId).moduleInfo.Popup;
        onShowNamedQueries(expression, namedqueryPopuName);
    };
    const suspendGridFilter = () => {
        adaptable.api.gridFilterApi.suspendGridFilter();
    };
    const unSuspendGridFilter = () => {
        adaptable.api.gridFilterApi.unSuspendGridFilter();
    };
    return {
        isReadOnly,
        namedQueryModuleAccessLevel,
        cachedQueries,
        expression,
        setExpression,
        isExpressionNamedQuery,
        isExpressionValid,
        isSuspended,
        gridFilter,
        isAdaptableReady,
        namedQueries,
        onAddCachedQuery,
        availableColumns,
        runQuery,
        clearQuery,
        onExpand: () => adaptable.api.gridFilterApi.openUIEditorForGridFilter(expression),
        saveQuery,
        suspendGridFilter,
        unSuspendGridFilter,
        setGridFilterExpression: (expression) => {
            adaptable.api.gridFilterApi.setGridFilterExpression(expression);
        },
        gridFilterAccessLevel,
        gridFilterHelpPage,
        gridFilterLinkDisabled,
    };
};
exports.useGridFilterExpressionEditor = useGridFilterExpressionEditor;
