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 { CustomSelectorInput, createFilter, CogIcon, clsx, PanelHeader, compareLabelFn, } from '@finos/legend-art';
import { observer } from 'mobx-react-lite';
import { QUERY_BUILDER_TEST_ID } from '../__lib__/QueryBuilderTesting.js';
import { LATEST_DATE, PrimitiveInstanceValue, VariableExpression, PackageableElementExplicitReference, RuntimePointer, VARIABLE_REFERENCE_TOKEN, isElementDeprecated, PrimitiveType, } from '@finos/legend-graph';
import { useApplicationStore } from '@finos/legend-application';
import { buildElementOption, getPackageableElementOptionFormatter, } from '@finos/legend-lego/graph-editor';
export const getParameterValue = (parameter) => {
    if (parameter instanceof VariableExpression) {
        return `${VARIABLE_REFERENCE_TOKEN}${parameter.name}`;
    }
    else {
        if (parameter instanceof PrimitiveInstanceValue &&
            parameter.genericType.value.rawType === PrimitiveType.STRICTDATE) {
            return parameter.values[0];
        }
        else if (parameter instanceof PrimitiveInstanceValue &&
            parameter.genericType.value.rawType === PrimitiveType.LATESTDATE) {
            return LATEST_DATE;
        }
        return '(unknown)';
    }
};
const generateClassLabel = (val, queryBuilderState) => {
    const isDeprecatedClass = isElementDeprecated(val, queryBuilderState.graphManagerState.graph);
    return (_jsx("div", { className: clsx('query-builder__setup__class-option-label', {
            'query-builder__setup__class-option-label--deprecated': isDeprecatedClass,
        }), children: _jsx("div", { className: "query-builder__setup__class-option-label__name", children: val.name }) }));
};
export const QueryBuilderClassSelector = observer((props) => {
    const { queryBuilderState, classes, onClassChange, noMatchMessage } = props;
    const applicationStore = useApplicationStore();
    // class
    const elementFilterOption = createFilter({
        ignoreCase: true,
        ignoreAccents: false,
        stringify: (option) => option.data.value.path,
    });
    const classOptions = classes
        .toSorted((a, b) => a.name.localeCompare(b.name))
        .map((_class) => ({
        value: _class,
        label: generateClassLabel(_class, queryBuilderState),
    }));
    const selectedClassOption = queryBuilderState.sourceClass
        ? {
            value: queryBuilderState.sourceClass,
            label: generateClassLabel(queryBuilderState.sourceClass, queryBuilderState),
        }
        : null;
    const changeClass = (val) => {
        if (val.value === queryBuilderState.sourceElement) {
            return;
        }
        queryBuilderState.changeSourceElement(val.value);
        onClassChange?.(val.value);
    };
    return (_jsx("div", { className: "query-builder__setup__config-group query-builder__setup__config-group--class", children: _jsxs("div", { className: "query-builder__setup__config-group__item", children: [_jsx("label", { className: "btn--sm query-builder__setup__config-group__item__label", title: "entity", htmlFor: "query-builder__setup__class-selector", children: "Entity" }), _jsx(CustomSelectorInput, { inputId: "query-builder__setup__class-selector", className: "panel__content__form__section__dropdown query-builder__setup__config-group__item__selector query-builder__setup__config-group__item__selector__milestoned", placeholder: classOptions.length
                        ? 'Choose an entity...'
                        : (noMatchMessage ?? 'No entity found'), disabled: classOptions.length < 1 ||
                        (classOptions.length === 1 && Boolean(selectedClassOption)), noMatchMessage: noMatchMessage, options: classOptions, onChange: changeClass, value: selectedClassOption, darkMode: !applicationStore.layoutService
                        .TEMPORARY__isLightColorThemeEnabled, filterOption: elementFilterOption, formatOptionLabel: getPackageableElementOptionFormatter({
                        darkMode: !applicationStore.layoutService
                            .TEMPORARY__isLightColorThemeEnabled,
                    }) })] }) }));
});
export const buildRuntimeValueOption = (runtimeValue) => ({
    value: runtimeValue,
    label: runtimeValue instanceof RuntimePointer
        ? runtimeValue.packageableRuntime.value.name
        : 'custom',
});
export const getRuntimeOptionFormatter = (props) => function RuntimeOptionLabel(option) {
    if (option.value instanceof RuntimePointer) {
        const runtimePointer = option.value;
        return getPackageableElementOptionFormatter(props)(buildElementOption(runtimePointer.packageableRuntime.value));
    }
    return option.value instanceof RuntimePointer ? (option.value.packageableRuntime.value.name) : (_jsxs("div", { className: "query-builder__setup__runtime-option--custom", children: [_jsx(CogIcon, {}), _jsx("div", { className: "query-builder__setup__runtime-option--custom__label", children: "custom" })] }));
};
const BasicQueryBuilderSetup = observer((props) => {
    const { queryBuilderState } = props;
    const applicationStore = useApplicationStore();
    // classes
    const classes = queryBuilderState.graphManagerState.usableClasses;
    // mapping
    const mappingOptions = queryBuilderState.graphManagerState.usableMappings
        .map(buildElementOption)
        .sort(compareLabelFn);
    const selectedMappingOption = queryBuilderState.executionContextState
        .mapping
        ? buildElementOption(queryBuilderState.executionContextState.mapping)
        : null;
    const changeMapping = (val) => {
        if (!queryBuilderState.sourceElement ||
            val.value === queryBuilderState.executionContextState.mapping ||
            queryBuilderState.isMappingReadOnly) {
            return;
        }
        queryBuilderState.changeMapping(val.value);
    };
    const mappingFilterOption = createFilter({
        ignoreCase: true,
        ignoreAccents: false,
        stringify: (option) => option.data.value.path,
    });
    // runtime
    const runtimeOptions = queryBuilderState.graphManagerState.usableRuntimes
        .map((rt) => new RuntimePointer(PackageableElementExplicitReference.create(rt)))
        .map(buildRuntimeValueOption)
        .sort(compareLabelFn);
    const selectedRuntimeOption = queryBuilderState.executionContextState
        .runtimeValue
        ? buildRuntimeValueOption(queryBuilderState.executionContextState.runtimeValue)
        : null;
    const changeRuntime = (val) => {
        if (val.value === queryBuilderState.executionContextState.runtimeValue ||
            queryBuilderState.isRuntimeReadOnly) {
            return;
        }
        queryBuilderState.changeRuntime(val.value);
    };
    const runtimeFilterOption = createFilter({
        ignoreCase: true,
        ignoreAccents: false,
        stringify: (option) => option.data.value instanceof RuntimePointer
            ? option.data.value.packageableRuntime.value.path
            : 'custom',
    });
    return (_jsxs("div", { className: "query-builder__setup__config-group", children: [_jsx(PanelHeader, { title: "properties" }), _jsxs("div", { className: "query-builder__setup__config-group__content", children: [_jsxs("div", { className: "query-builder__setup__config-group__item", children: [_jsx("label", { className: "btn--sm query-builder__setup__config-group__item__label", title: "mapping", htmlFor: "query-builder__setup__mapping-selector", children: "Mapping" }), _jsx(CustomSelectorInput, { inputId: "query-builder__setup__mapping-selector", className: "panel__content__form__section__dropdown query-builder__setup__config-group__item__selector", placeholder: mappingOptions.length
                                    ? 'Choose a mapping...'
                                    : 'No mapping found', disabled: queryBuilderState.isMappingReadOnly ||
                                    !queryBuilderState.sourceElement, options: mappingOptions, onChange: changeMapping, value: selectedMappingOption, darkMode: !applicationStore.layoutService
                                    .TEMPORARY__isLightColorThemeEnabled, filterOption: mappingFilterOption, formatOptionLabel: getPackageableElementOptionFormatter({
                                    darkMode: !applicationStore.layoutService
                                        .TEMPORARY__isLightColorThemeEnabled,
                                }) })] }), _jsxs("div", { className: "query-builder__setup__config-group__item", children: [_jsx("label", { className: "btn--sm query-builder__setup__config-group__item__label", title: "runtime", htmlFor: "query-builder__setup__runtime-selector", children: "Runtime" }), _jsx(CustomSelectorInput, { inputId: "query-builder__setup__runtime-selector", className: "panel__content__form__section__dropdown query-builder__setup__config-group__item__selector", placeholder: runtimeOptions.length
                                    ? 'Choose a runtime...'
                                    : 'No runtime found', disabled: queryBuilderState.isRuntimeReadOnly ||
                                    !queryBuilderState.sourceElement ||
                                    !queryBuilderState.executionContextState.mapping, options: runtimeOptions, onChange: changeRuntime, value: selectedRuntimeOption, darkMode: !applicationStore.layoutService
                                    .TEMPORARY__isLightColorThemeEnabled, filterOption: runtimeFilterOption, formatOptionLabel: getRuntimeOptionFormatter({
                                    darkMode: !applicationStore.layoutService
                                        .TEMPORARY__isLightColorThemeEnabled,
                                }) })] }), _jsx("div", { className: "query-builder__setup__config-group__item", children: _jsx(QueryBuilderClassSelector, { queryBuilderState: queryBuilderState, classes: classes }) })] })] }));
});
export const QueryBuilderSidebar = observer((props) => {
    const { queryBuilderState, children } = props;
    const applicationStore = useApplicationStore();
    const extraTemplateQueryPanelContentRenderers = applicationStore.pluginManager
        .getApplicationPlugins()
        .flatMap((plugin) => plugin.getExtraTemplateQueryPanelContentRenderer?.() ?? []);
    // Try each renderer until one returns a non-undefined result.
    let templateQueryPanelContentTab = _jsx(_Fragment, {});
    for (const renderer of extraTemplateQueryPanelContentRenderers) {
        const result = renderer(queryBuilderState);
        if (result !== undefined) {
            templateQueryPanelContentTab = result;
            break;
        }
    }
    return (_jsxs("div", { className: clsx('query-builder__side-bar', queryBuilderState.sideBarClassName), children: [_jsx("div", { "data-testid": QUERY_BUILDER_TEST_ID.QUERY_BUILDER_SETUP, className: "panel query-builder__setup", children: _jsx("div", { className: "panel__content query-builder__setup__content", children: queryBuilderState.TEMPORARY__setupPanelContentRenderer?.() ?? (_jsx(BasicQueryBuilderSetup, { queryBuilderState: queryBuilderState })) }) }), _jsx("div", { "data-testid": QUERY_BUILDER_TEST_ID.QUERY_BUILDER_TEMPLATE_QUERY_PANE, className: "query-builder__template-query", children: templateQueryPanelContentTab }), _jsx("div", { className: "query-builder__side-bar__content", children: children })] }));
});
//# sourceMappingURL=QueryBuilderSideBar.js.map