"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 InternalRedux = tslib_1.__importStar(require("../../Redux/ActionsReducers/InternalRedux"));
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 = () => {
    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?.IsReadOnly);
    const gridFilter = currentLayout?.GridFilter;
    const [isAdaptableReady, setIsAdaptableReady] = React.useState(false);
    const [expression, setExpression] = React.useState(() => {
        return adaptable.api.filterApi.gridFilterApi.getCurrentGridFilterExpression();
    });
    const namedQueries = (0, react_redux_1.useSelector)((state) => state.NamedQuery.NamedQueries) ?? [];
    const cachedQueries = (0, react_redux_1.useSelector)((state) => state.Internal.CachedQueries) ?? [];
    const isSuspended = gridFilter?.IsSuspended ?? false;
    const onAddCachedQuery = (cachedQuery) => {
        dispatch(InternalRedux.CachedQueryAdd(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(() => {
        if (gridFilter?.Expression != expression) {
            setExpression(gridFilter?.Expression ?? '');
        }
    }, [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.filterApi.gridFilterApi.clearGridFilter();
        setExpression('');
    };
    const runQuery = (newExpression = expression) => {
        if (StringExtensions_1.default.IsNullOrEmpty(newExpression) &&
            StringExtensions_1.default.IsNotNullOrEmpty(gridFilter?.Expression)) {
            // user pressed enter key with an empty input => clear existing expression
            adaptable.api.filterApi.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.filterApi.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.filterApi.gridFilterApi.suspendGridFilter();
    };
    const unSuspendGridFilter = () => {
        adaptable.api.filterApi.gridFilterApi.unSuspendGridFilter();
    };
    return {
        isReadOnly,
        namedQueryModuleAccessLevel,
        cachedQueries,
        expression,
        setExpression,
        isExpressionNamedQuery,
        isExpressionValid,
        isSuspended,
        gridFilter,
        isAdaptableReady,
        namedQueries,
        onAddCachedQuery,
        availableColumns,
        runQuery,
        clearQuery,
        onExpand: () => adaptable.api.filterApi.gridFilterApi.openUIEditorForGridFilter(expression),
        saveQuery,
        suspendGridFilter,
        unSuspendGridFilter,
        setGridFilterExpression: (expression) => {
            adaptable.api.filterApi.gridFilterApi.setGridFilterExpression(expression);
        },
        gridFilterAccessLevel,
        gridFilterHelpPage,
        gridFilterLinkDisabled,
    };
};
exports.useGridFilterExpressionEditor = useGridFilterExpressionEditor;
