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 { observer } from 'mobx-react-lite';
import { BlankPanelPlaceholder, BlankPanelContent, ContextMenu, CustomSelectorInput, Dialog, ErrorWarnIcon, FilledWindowMaximizeIcon, MenuContent, MenuContentItem, Modal, ModalBody, ModalFooter, ModalFooterButton, ModalHeader, ModalTitle, Panel, PanelFormTextField, PanelHeader, PanelHeaderActionItem, PanelHeaderActions, PlayIcon, PlusIcon, RefreshIcon, ResizablePanel, ResizablePanelGroup, ResizablePanelSplitter, ResizablePanelSplitterLine, RunAllIcon, RunErrorsIcon, TimesIcon, clsx, } from '@finos/legend-art';
import { forwardRef, useEffect, useRef, useState } from 'react';
import { DataElementReference, PackageableElementExplicitReference, RelationalCSVData, ModelStoreData, ExternalFormatData, ModelEmbeddedData, PrimitiveInstanceValue, PrimitiveType, } from '@finos/legend-graph';
import { FunctionValueSpecificationTestParameterState, } from '../../../../../stores/editor/editor-state/element-editor-state/function-activator/testable/FunctionTestableState.js';
import { TESTABLE_RESULT, getTestableResultFromTestResult, } from '../../../../../stores/editor/sidebar-state/testable/GlobalTestRunnerState.js';
import { flowResult } from 'mobx';
import { getTestableResultIcon } from '../../../side-bar/testable/GlobalTestRunner.js';
import { ExternalFormatParameterEditorModal, RenameModal, SharedDataElementModal, TestAssertionEditor, } from '../../testable/TestableSharedComponents.js';
import { filterByType, prettyCONSTName, returnUndefOnError, } from '@finos/legend-shared';
import { EmbeddedDataCreatorFromEmbeddedData, validateTestableId, getContentTypeWithParamFromQuery, } from '../../../../../stores/editor/utils/TestableUtils.js';
import { EmbeddedDataEditor } from '../../data-editor/EmbeddedDataEditor.js';
import { LEGEND_STUDIO_APPLICATION_NAVIGATION_CONTEXT_KEY } from '../../../../../__lib__/LegendStudioApplicationNavigationContext.js';
import { useApplicationNavigationContext } from '@finos/legend-application';
import { BasicValueSpecificationEditor, instanceValue_setValue, } from '@finos/legend-query-builder';
import { TESTABLE_TEST_TAB } from '../../../../../stores/editor/editor-state/element-editor-state/testable/TestableEditorState.js';
import { atomicTest_setDoc } from '../../../../../stores/graph-modifier/Testable_GraphModifierHelper.js';
const FunctionTestableContextMenu = observer(forwardRef(function TestContainerContextMenu(props, ref) {
    const { addName, add, rename, _delete } = props;
    const addTest = () => {
        add?.();
    };
    const remove = () => _delete?.();
    const handleRename = () => rename?.();
    return (_jsxs(MenuContent, { ref: ref, children: [rename && (_jsx(MenuContentItem, { onClick: handleRename, children: "Rename" })), _delete && _jsx(MenuContentItem, { onClick: remove, children: "Delete" }), addName && rename && (_jsx(MenuContentItem, { onClick: addTest, children: `Add ${addName}` }))] }));
}));
const FunctionTestDataStateEditor = observer((props) => {
    const { functionTestSuiteState, storeTestDataState } = props;
    const functionTestableState = functionTestSuiteState.functionTestableState;
    const isReadOnly = functionTestableState.functionEditorState.isReadOnly;
    const embeddedState = storeTestDataState.embeddedEditorState;
    const currentData = embeddedState.embeddedData;
    const isUsingReference = currentData instanceof DataElementReference;
    const open = () => storeTestDataState.setDataElementModal(true);
    const close = () => storeTestDataState.setDataElementModal(false);
    const changeToUseMyOwn = () => {
        if (isUsingReference) {
            const newBare = returnUndefOnError(() => currentData.accept_EmbeddedDataVisitor(new EmbeddedDataCreatorFromEmbeddedData(functionTestableState.editorStore)));
            if (newBare) {
                storeTestDataState.changeEmbeddedData(newBare);
            }
        }
    };
    const sharedDataHandler = (val) => {
        const dataRef = new DataElementReference();
        dataRef.dataElement = PackageableElementExplicitReference.create(val);
        const dataElementValue = val.data;
        let embeddedData = dataRef;
        if (currentData instanceof ModelStoreData &&
            dataElementValue instanceof ExternalFormatData) {
            const modelStoreVal = currentData.modelData?.[0];
            if (modelStoreVal instanceof ModelEmbeddedData) {
                const newModelEmbeddedData = new ModelEmbeddedData();
                newModelEmbeddedData.model =
                    PackageableElementExplicitReference.create(modelStoreVal.model.value);
                newModelEmbeddedData.data = dataRef;
                const modelStoreData = new ModelStoreData();
                modelStoreData.modelData = [newModelEmbeddedData];
                embeddedData = modelStoreData;
            }
        }
        storeTestDataState.changeEmbeddedData(embeddedData);
    };
    const dataElements = functionTestSuiteState.editorStore.graphManagerState.graph.dataElements;
    const filter = (val) => {
        const dataElementData = val.data;
        if (currentData instanceof RelationalCSVData) {
            if (dataElementData instanceof RelationalCSVData) {
                return true;
            }
            return false;
        }
        else if (currentData instanceof ModelStoreData) {
            if (dataElementData instanceof ExternalFormatData ||
                dataElementData instanceof ModelStoreData) {
                return true;
            }
            return false;
        }
        return true;
    };
    return (_jsxs("div", { className: "service-test-data-editor", children: [_jsxs("div", { className: "function-testable-editor__header", children: [_jsx("div", { className: "function-testable-editor__header__title", children: _jsx("div", { className: "function-testable-editor__header__title__label", children: "input data" }) }), _jsx("div", { className: "panel__header__actions", children: isUsingReference ? (_jsx("button", { className: "panel__header__action service-execution-editor__test-data__generate-btn", onClick: changeToUseMyOwn, disabled: !isUsingReference, title: "Use own data", tabIndex: -1, children: _jsx("div", { className: "service-execution-editor__test-data__generate-btn__label", children: _jsx("div", { className: "service-execution-editor__test-data__generate-btn__label__title", children: "Own Data" }) }) })) : (_jsx("button", { className: "panel__header__action service-execution-editor__test-data__generate-btn", onClick: open, title: "Use Shared Data via Defined Data Element", disabled: !dataElements.length, tabIndex: -1, children: _jsx("div", { className: "service-execution-editor__test-data__generate-btn__label", children: _jsx("div", { className: "service-execution-editor__test-data__generate-btn__label__title", children: "Shared Data" }) }) })) })] }), storeTestDataState.dataElementModal && (_jsx(SharedDataElementModal, { isReadOnly: false, editorStore: storeTestDataState.editorStore, close: close, filterBy: filter, handler: sharedDataHandler })), _jsx(EmbeddedDataEditor, { isReadOnly: isReadOnly, embeddedDataEditorState: storeTestDataState.embeddedEditorState })] }));
});
const FunctionTestParameterEditor = observer((props) => {
    const { functionTestState, paramState, isReadOnly, contentTypeParamPair } = props;
    const [showPopUp, setShowPopUp] = useState(false);
    const paramIsRequired = paramState.varExpression.multiplicity.lowerBound > 0;
    const type = contentTypeParamPair
        ? contentTypeParamPair.contentType
        : (paramState.varExpression.genericType?.value.rawType.name ?? 'unknown');
    const paramValue = paramState.varExpression.genericType?.value.rawType === PrimitiveType.BYTE
        ? atob(paramState.valueSpec
            .values[0])
        : paramState.valueSpec
            .values[0];
    const openInPopUp = () => setShowPopUp(!showPopUp);
    const closePopUp = () => setShowPopUp(false);
    const updateParamValue = (val) => {
        if (paramState.valueSpec instanceof PrimitiveInstanceValue) {
            instanceValue_setValue(paramState.valueSpec, paramState.varExpression.genericType?.value.rawType ===
                PrimitiveType.BYTE
                ? btoa(val)
                : val, 0, functionTestState.editorStore.changeDetectionState.observerContext);
            paramState.updateValueSpecification(paramState.valueSpec);
        }
    };
    return (_jsxs("div", { className: "panel__content__form__section", children: [_jsxs("div", { className: "panel__content__form__section__header__label", children: [paramState.parameterValue.name, _jsx("button", { className: clsx('type-tree__node__type__label', {}), tabIndex: -1, title: type, children: type })] }), _jsx(_Fragment, { children: contentTypeParamPair ? (_jsxs("div", { className: "service-test-editor__setup__parameter__code-editor", children: [_jsx("textarea", { className: "panel__content__form__section__textarea value-spec-editor__input", spellCheck: false, value: paramValue, placeholder: paramState.valueSpec
                                .values[0] === ''
                                ? '(empty)'
                                : undefined, onChange: (event) => {
                                updateParamValue(event.target.value);
                            } }), showPopUp && (_jsx(ExternalFormatParameterEditorModal, { valueSpec: paramState.valueSpec, varExpression: paramState.varExpression, isReadOnly: isReadOnly, onClose: closePopUp, updateParamValue: updateParamValue, contentTypeParamPair: contentTypeParamPair })), _jsxs("div", { className: "service-test-editor__setup__parameter__value__actions", children: [_jsx("button", { className: clsx('service-test-editor__setup__parameter__code-editor__expand-btn'), onClick: openInPopUp, tabIndex: -1, title: "Open in a popup...", children: _jsx(FilledWindowMaximizeIcon, {}) }), _jsx("button", { className: clsx('btn--icon btn--dark btn--sm service-test-editor__setup__parameter__code-editor__expand-btn'), disabled: isReadOnly || paramIsRequired, onClick: () => functionTestState.removeParamValueState(paramState), tabIndex: -1, title: paramIsRequired ? 'Parameter Required' : 'Remove Parameter', children: _jsx(TimesIcon, {}) })] })] })) : (_jsxs("div", { className: "service-test-editor__setup__parameter__value", children: [_jsx(BasicValueSpecificationEditor, { valueSpecification: paramState.valueSpec, setValueSpecification: (val) => {
                                paramState.updateValueSpecification(val);
                            }, graph: functionTestState.editorStore.graphManagerState.graph, observerContext: functionTestState.editorStore.changeDetectionState
                                .observerContext, typeCheckOption: {
                                expectedType: paramState.varExpression.genericType?.value.rawType ??
                                    PrimitiveType.STRING,
                            }, className: "query-builder__parameters__value__editor", resetValue: () => {
                                paramState.resetValueSpec();
                            } }), _jsx("div", { className: "service-test-editor__setup__parameter__value__actions", children: _jsx("button", { className: "btn--icon btn--dark btn--sm", disabled: isReadOnly || paramIsRequired, onClick: () => functionTestState.removeParamValueState(paramState), tabIndex: -1, title: paramIsRequired ? 'Parameter Required' : 'Remove Parameter', children: _jsx(TimesIcon, {}) }) })] })) })] }, paramState.parameterValue.name));
});
const NewParameterModal = observer((props) => {
    const { functionTestState, isReadOnly } = props;
    const applicationStore = functionTestState.editorStore.applicationStore;
    const currentOption = {
        value: functionTestState.newParameterValueName,
        label: functionTestState.newParameterValueName,
    };
    const options = functionTestState.newParamOptions;
    const closeModal = () => functionTestState.setShowNewParameterModal(false);
    const onChange = (val) => {
        if (val === null) {
            functionTestState.setNewParameterValueName('');
        }
        else if (val.value !== functionTestState.newParameterValueName) {
            functionTestState.setNewParameterValueName(val.value);
        }
    };
    return (_jsx(Dialog, { open: functionTestState.showNewParameterModal, onClose: closeModal, classes: { container: 'search-modal__container' }, slotProps: {
            paper: {
                classes: { root: 'search-modal__inner-container' },
            },
        }, children: _jsxs("form", { onSubmit: (event) => {
                event.preventDefault();
                functionTestState.addParameterValue();
            }, className: "modal modal--dark search-modal", children: [_jsx("div", { className: "modal__title", children: "New Test Parameter Value " }), _jsx(CustomSelectorInput, { className: "panel__content__form__section__dropdown", options: options, onChange: onChange, value: currentOption, escapeClearsValue: true, darkMode: !applicationStore.layoutService
                        .TEMPORARY__isLightColorThemeEnabled, disabled: isReadOnly }), _jsx("div", { className: "search-modal__actions", children: _jsx("button", { className: "btn btn--dark", disabled: isReadOnly, children: "Add" }) })] }) }));
});
const FunctionTestEditor = observer((props) => {
    const { functionTestState } = props;
    const selectedTab = functionTestState.selectedTab;
    const addParameter = () => {
        functionTestState.setShowNewParameterModal(true);
    };
    const generateParameterValues = () => {
        functionTestState.generateTestParameterValues();
    };
    useEffect(() => {
        functionTestState.syncWithQuery();
    }, [functionTestState]);
    return (_jsxs("div", { className: "function-test-editor panel", children: [_jsx("div", { className: "panel__header", children: _jsx("div", { className: "panel__header service-test-editor__header--with-tabs", children: _jsx("div", { className: "uml-element-editor__tabs", children: Object.values(TESTABLE_TEST_TAB).map((tab) => (_jsx("div", { onClick: () => functionTestState.setSelectedTab(tab), className: clsx('service-test-editor__tab', {
                                'service-test-editor__tab--active': tab === functionTestState.selectedTab,
                            }), children: prettyCONSTName(tab) }, tab))) }) }) }), _jsxs("div", { className: "panel", children: [selectedTab === TESTABLE_TEST_TAB.ASSERTION &&
                        functionTestState.selectedAsertionState && (_jsx(TestAssertionEditor, { testAssertionState: functionTestState.selectedAsertionState })), selectedTab === TESTABLE_TEST_TAB.SETUP &&
                        functionTestState.selectedAsertionState && (_jsxs(_Fragment, { children: [_jsx("div", { className: "function-test-editor__doc", children: _jsxs("div", { className: "panel__content__form__section", children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Test Documentation" }), _jsx("textarea", { className: "panel__content__form__section__textarea mapping-testable-editor__doc__textarea", spellCheck: false, value: functionTestState.test.doc ?? '', onChange: (event) => {
                                                atomicTest_setDoc(functionTestState.test, event.target.value ? event.target.value : undefined);
                                            } })] }) }), Boolean(functionTestState.parameterValueStates.length) && (_jsxs("div", { className: "service-test-data-editor panel", children: [_jsxs("div", { className: "service-test-suite-editor__header", children: [_jsx("div", { className: "service-test-suite-editor__header__title", children: _jsx("div", { className: "service-test-suite-editor__header__title__label", children: "parameters" }) }), _jsxs("div", { className: "panel__header__actions", children: [_jsx("button", { className: "panel__header__action service-execution-editor__test-data__generate-btn", onClick: generateParameterValues, disabled: !functionTestState.newParamOptions.length, title: "Generate test parameter values", tabIndex: -1, children: _jsxs("div", { className: "service-execution-editor__test-data__generate-btn__label", children: [_jsx(RefreshIcon, { className: "service-execution-editor__test-data__generate-btn__label__icon" }), _jsx("div", { className: "service-execution-editor__test-data__generate-btn__label__title", children: "Generate" })] }) }), _jsx("button", { className: "panel__header__action", tabIndex: -1, disabled: !functionTestState.newParamOptions.length, onClick: addParameter, title: "Add Parameter Value", children: _jsx(PlusIcon, {}) })] })] }), _jsx("div", { className: "service-test-editor__setup__parameters", children: functionTestState.parameterValueStates
                                            .filter(filterByType(FunctionValueSpecificationTestParameterState))
                                            .map((paramState) => (_jsx(FunctionTestParameterEditor, { isReadOnly: false, paramState: paramState, functionTestState: functionTestState, contentTypeParamPair: getContentTypeWithParamFromQuery(functionTestState.functionTestableState
                                                .functionEditorState.bodyExpressionSequence, functionTestState.functionTestableState
                                                .editorStore).find((pair) => pair.param === paramState.parameterValue.name) }, paramState.uuid))) }), functionTestState.showNewParameterModal && (_jsx(NewParameterModal, { functionTestState: functionTestState, isReadOnly: false }))] }))] }))] })] }));
});
const FunctionTestItem = observer((props) => {
    const { functionTestState, suiteState } = props;
    const functionTest = functionTestState.test;
    const isRunning = functionTestState.runningTestAction.isInProgress;
    const [isSelectedFromContextMenu, setIsSelectedFromContextMenu] = useState(false);
    const isReadOnly = suiteState.functionTestableState.functionEditorState.isReadOnly;
    const openTest = () => suiteState.changeTest(functionTest);
    const isActive = suiteState.selectTestState?.test === functionTest;
    const _testableResult = getTestableResultFromTestResult(functionTestState.testResultState.result);
    const testableResult = isRunning
        ? TESTABLE_RESULT.IN_PROGRESS
        : _testableResult;
    const resultIcon = getTestableResultIcon(testableResult);
    const onContextMenuOpen = () => setIsSelectedFromContextMenu(true);
    const onContextMenuClose = () => setIsSelectedFromContextMenu(false);
    const add = () => {
        // TODO
    };
    const _delete = () => {
        suiteState.deleteTest(functionTest);
    };
    const rename = () => {
        suiteState.functionTestableState.setRenameComponent(functionTest);
    };
    const runTest = () => {
        flowResult(functionTestState.runTest()).catch(functionTestState.editorStore.applicationStore.alertUnhandledError);
    };
    return (_jsx(ContextMenu, { className: clsx('testable-test-explorer__item', {
            'testable-test-explorer__item--selected-from-context-menu': !isActive && isSelectedFromContextMenu,
        }, { 'testable-test-explorer__item--active': isActive }), disabled: isReadOnly, content: _jsx(FunctionTestableContextMenu, { addName: "Test", add: add, _delete: _delete, rename: rename }), menuProps: { elevation: 7 }, onOpen: onContextMenuOpen, onClose: onContextMenuClose, children: _jsxs("div", { className: clsx('testable-test-explorer__item__label'), onClick: openTest, tabIndex: -1, children: [_jsx("div", { className: "testable-test-explorer__item__label__icon", children: resultIcon }), _jsx("div", { className: "testable-test-explorer__item__label__text", children: functionTest.id }), _jsx("div", { className: "mapping-test-explorer__item__actions", children: _jsx("button", { className: "mapping-test-explorer__item__action mapping-test-explorer__run-test-btn", onClick: runTest, disabled: functionTestState.runningTestAction.isInProgress, tabIndex: -1, title: `Run ${functionTestState.test.id}`, children: _jsx(PlayIcon, {}) }) })] }) }));
});
const CreateTestModal = observer((props) => {
    const { functionSuiteState } = props;
    const applicationStore = functionSuiteState.editorStore.applicationStore;
    const suite = functionSuiteState.suite;
    // test name
    const [id, setId] = useState(undefined);
    const isValid = id && !id.includes(' ');
    const errorMessage = validateTestableId(id, suite.tests.map((t) => t.id));
    const close = () => functionSuiteState.setShowModal(false);
    const create = () => {
        if (id) {
            flowResult(functionSuiteState.addNewTest(id))
                .then(() => close())
                .catch(functionSuiteState.editorStore.applicationStore.alertUnhandledError);
        }
    };
    return (_jsx(Dialog, { open: functionSuiteState.showCreateModal, onClose: close, classes: { container: 'search-modal__container' }, slotProps: {
            paper: {
                classes: { root: 'search-modal__inner-container' },
            },
        }, children: _jsxs(Modal, { darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled, children: [_jsx(ModalHeader, { children: _jsx(ModalTitle, { title: "Create Function Test" }) }), _jsx(ModalBody, { children: _jsx(PanelFormTextField, { name: "Name", prompt: "", value: id, update: (value) => setId(value ?? ''), errorMessage: errorMessage }) }), _jsxs(ModalFooter, { children: [_jsx(ModalFooterButton, { disabled: !isValid, onClick: create, text: "Create" }), _jsx(ModalFooterButton, { onClick: close, text: "Close", type: "secondary" })] })] }) }));
});
// ──────────────────────────────────────────────────────────────────────────────
// Add Element Modal
// ──────────────────────────────────────────────────────────────────────────────
const AddDataElementModal = observer((props) => {
    const { functionTestSuiteState } = props;
    const dataState = functionTestSuiteState.dataState;
    const applicationStore = functionTestSuiteState.editorStore.applicationStore;
    const options = dataState.availableElementsToAdd.map((e) => ({
        value: e.path,
        label: e.path,
    }));
    const [selectedPath, setSelectedPath] = useState(options[0]?.value);
    const close = () => dataState.setShowAddElementModal(false);
    const add = () => {
        if (selectedPath) {
            dataState.addDataElement(selectedPath);
            close();
        }
    };
    const onChange = (val) => {
        setSelectedPath(val?.value);
    };
    return (_jsx(Dialog, { open: dataState.showAddElementModal, onClose: close, classes: { container: 'search-modal__container' }, slotProps: {
            paper: {
                classes: { root: 'search-modal__inner-container' },
            },
        }, children: _jsxs(Modal, { darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled, children: [_jsx(ModalHeader, { children: _jsx(ModalTitle, { title: "Add Element" }) }), _jsx(ModalBody, { children: _jsx(CustomSelectorInput, { className: "panel__content__form__section__dropdown", options: options, onChange: onChange, value: selectedPath
                            ? { value: selectedPath, label: selectedPath }
                            : null, placeholder: "Select element...", darkMode: !applicationStore.layoutService
                            .TEMPORARY__isLightColorThemeEnabled }) }), _jsxs(ModalFooter, { children: [_jsx(ModalFooterButton, { disabled: !selectedPath, onClick: add, text: "Add" }), _jsx(ModalFooterButton, { onClick: close, text: "Close", type: "secondary" })] })] }) }));
});
// ──────────────────────────────────────────────────────────────────────────────
// Test Data Editor (left panel) — elements list + per-element data editor
// ──────────────────────────────────────────────────────────────────────────────
const FunctionTestDataPanel = observer((props) => {
    const { functionTestSuiteState } = props;
    const dataState = functionTestSuiteState.dataState;
    const hasIngestOrDataProductAccessors = functionTestSuiteState.functionTestableState
        .resolvedIngestOrDataProductAccessors.length > 0;
    const hasTestData = Boolean(dataState.dataHolder.testData?.length);
    const addStoreTestData = () => {
        if (!dataState.availableElementsToAdd.length) {
            functionTestSuiteState.editorStore.applicationStore.notificationService.notifyWarning(hasIngestOrDataProductAccessors
                ? `All referenced elements' data is already present`
                : `No elements available to add`);
            return;
        }
        dataState.setShowAddElementModal(true);
    };
    return (_jsxs("div", { className: clsx('service-test-data-editor panel', {
            'service-test-data-editor--no-data': !hasTestData,
        }), children: [_jsx("div", { className: "service-test-data-editor__data", children: _jsxs(ResizablePanelGroup, { orientation: "vertical", children: [_jsxs(ResizablePanel, { minSize: 100, size: 180, children: [_jsxs("div", { className: "binding-editor__header", children: [_jsx("div", { className: "binding-editor__header__title", children: _jsx("div", { className: "panel__header__title__content", children: "Test Data" }) }), _jsx("div", { className: "panel__header__actions", children: _jsx("button", { className: "panel__header__action", tabIndex: -1, onClick: addStoreTestData, title: "Add Element", children: _jsx(PlusIcon, {}) }) })] }), !hasTestData ? (_jsxs("div", { className: "service-test-data-editor__warning", children: [_jsx(ErrorWarnIcon, {}), _jsx("span", { children: "Add an element to configure test data" })] })) : (_jsx("div", { children: (dataState.dataHolder.testData ?? []).map((td) => (_jsx("div", { className: clsx('testable-test-explorer__item', {
                                            'testable-test-explorer__item--active': dataState.selectedDataState?.storeTestData === td,
                                        }), children: _jsxs("div", { className: "testable-test-explorer__item__label", onClick: () => dataState.openStoreTestData(td), tabIndex: -1, children: [_jsx("div", { className: "testable-test-explorer__item__label__text", children: td.element.value.path }), _jsx("div", { className: "mapping-test-explorer__item__actions", children: _jsx("button", { className: "mapping-test-explorer__item__action", onClick: (e) => {
                                                            e.stopPropagation();
                                                            dataState.deleteStoreTestData(td);
                                                        }, tabIndex: -1, title: "Delete", children: _jsx(TimesIcon, {}) }) })] }) }, td.element.value.path))) }))] }), _jsx(ResizablePanelSplitter, { children: _jsx(ResizablePanelSplitterLine, { color: "var(--color-dark-grey-200)" }) }), _jsx(ResizablePanel, { minSize: 200, children: dataState.selectedDataState ? (_jsx(FunctionTestDataStateEditor, { functionTestSuiteState: functionTestSuiteState, storeTestDataState: dataState.selectedDataState })) : (_jsx(BlankPanelContent, { children: "Select an element to configure its test data" })) })] }) }), dataState.showAddElementModal && (_jsx(AddDataElementModal, { functionTestSuiteState: functionTestSuiteState }))] }));
});
// ──────────────────────────────────────────────────────────────────────────────
// Tests Editor (right panel) — tests list + test detail (assertion/setup)
// ──────────────────────────────────────────────────────────────────────────────
const FunctionTestsPanel = observer((props) => {
    const { functionTestSuiteState } = props;
    const editorStore = functionTestSuiteState.editorStore;
    const isReadOnly = functionTestSuiteState.functionTestableState.functionEditorState
        .isReadOnly;
    const selectedTestState = functionTestSuiteState.selectTestState;
    const addTest = () => {
        functionTestSuiteState.setShowModal(true);
    };
    const runTests = () => {
        flowResult(functionTestSuiteState.runSuite()).catch(editorStore.applicationStore.alertUnhandledError);
    };
    const runFailingTests = () => {
        flowResult(functionTestSuiteState.runFailingTests()).catch(editorStore.applicationStore.alertUnhandledError);
    };
    return (_jsxs("div", { className: "panel service-test-editor", children: [_jsx("div", { className: "service-test-editor__content", children: _jsxs(ResizablePanelGroup, { orientation: "vertical", children: [_jsxs(ResizablePanel, { minSize: 100, size: 200, children: [_jsxs("div", { className: "binding-editor__header", children: [_jsx("div", { className: "binding-editor__header__title", children: _jsx("div", { className: "panel__header__title__content", children: "Tests" }) }), _jsxs("div", { className: "panel__header__actions", children: [_jsx("button", { className: "panel__header__action testable-test-explorer__play__all__icon", tabIndex: -1, onClick: runTests, title: "Run All Tests", children: _jsx(RunAllIcon, {}) }), _jsx("button", { className: "panel__header__action testable-test-explorer__play__all__icon", tabIndex: -1, onClick: runFailingTests, title: "Run All Failing Tests", children: _jsx(RunErrorsIcon, {}) }), !isReadOnly && (_jsx("button", { className: "panel__header__action", tabIndex: -1, onClick: addTest, title: "Add Function Test", children: _jsx(PlusIcon, {}) }))] })] }), _jsx("div", { children: functionTestSuiteState.testStates.map((test) => (_jsx(FunctionTestItem, { functionTestState: test, suiteState: functionTestSuiteState }, test.uuid))) })] }), _jsx(ResizablePanelSplitter, { children: _jsx(ResizablePanelSplitterLine, { color: "var(--color-dark-grey-200)" }) }), _jsx(ResizablePanel, { minSize: 56, children: selectedTestState ? (_jsx(FunctionTestEditor, { functionTestState: selectedTestState })) : (_jsx(BlankPanelPlaceholder, { text: "Select a test", tooltipText: "Select a test from the list above" })) })] }) }), functionTestSuiteState.showCreateModal && (_jsx(CreateTestModal, { functionSuiteState: functionTestSuiteState }))] }));
});
// ──────────────────────────────────────────────────────────────────────────────
// Suite Editor — horizontal split: test data (left) + tests (right)
// ──────────────────────────────────────────────────────────────────────────────
const FunctionTestSuiteEditor = observer((props) => {
    const { functionTestSuiteState } = props;
    const hasTestData = Boolean(functionTestSuiteState.dataState.dataHolder.testData?.length);
    const hasIngestOrDataProductAccessors = functionTestSuiteState.functionTestableState
        .resolvedIngestOrDataProductAccessors.length > 0;
    const showTestDataPanel = functionTestSuiteState.functionTestableState.containsRuntime ||
        hasIngestOrDataProductAccessors ||
        hasTestData;
    if (!showTestDataPanel) {
        // No test data — just show the tests panel full width
        return (_jsx("div", { className: "service-test-suite-editor", children: _jsx(FunctionTestsPanel, { functionTestSuiteState: functionTestSuiteState }) }));
    }
    return (_jsx("div", { className: "service-test-suite-editor", children: _jsxs(ResizablePanelGroup, { orientation: "horizontal", children: [_jsx(ResizablePanel, { size: 300, minSize: 28, children: _jsx(FunctionTestDataPanel, { functionTestSuiteState: functionTestSuiteState }) }), _jsx(ResizablePanelSplitter, { children: _jsx(ResizablePanelSplitterLine, { color: "var(--color-dark-grey-200)" }) }), _jsx(ResizablePanel, { minSize: 56, children: _jsx(FunctionTestsPanel, { functionTestSuiteState: functionTestSuiteState }) })] }) }));
});
// ──────────────────────────────────────────────────────────────────────────────
// Suite Tab Context Menu (rename/delete)
// ──────────────────────────────────────────────────────────────────────────────
const SuiteHeaderTabContextMenu = observer(forwardRef(function SuiteHeaderTabContextMenu(props, ref) {
    const { suite, functionTestableState } = props;
    const deleteSuite = () => {
        functionTestableState.deleteTestSuite(suite);
    };
    const rename = () => {
        functionTestableState.setRenameComponent(suite);
    };
    return (_jsxs(MenuContent, { ref: ref, children: [_jsx(MenuContentItem, { onClick: rename, children: "Rename" }), _jsx(MenuContentItem, { onClick: deleteSuite, children: "Delete" })] }));
}));
// ──────────────────────────────────────────────────────────────────────────────
// Create Suite Modal
// ──────────────────────────────────────────────────────────────────────────────
const CreateFunctionTestSuiteModal = observer((props) => {
    const { functionTestableEditorState } = props;
    const applicationStore = functionTestableEditorState.editorStore.applicationStore;
    const inputRef = useRef(null);
    const handleEnter = () => inputRef.current?.focus();
    const [suiteName, setSuiteName] = useState(undefined);
    const [testName, setTestName] = useState(undefined);
    const isValid = suiteName && testName;
    const close = () => functionTestableEditorState.setCreateSuite(false);
    const create = () => {
        if (suiteName && testName) {
            flowResult(functionTestableEditorState.createSuite(suiteName, testName)).catch(functionTestableEditorState.editorStore.applicationStore
                .alertUnhandledError);
        }
    };
    return (_jsx(Dialog, { open: true, onClose: close, classes: { container: 'search-modal__container' }, slotProps: {
            transition: {
                onEnter: handleEnter,
            },
            paper: {
                classes: { root: 'search-modal__inner-container' },
            },
        }, children: _jsxs(Modal, { darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled, children: [_jsx(ModalHeader, { children: _jsx(ModalTitle, { title: "Create Function Test Suite" }) }), _jsxs(ModalBody, { children: [_jsx(PanelFormTextField, { ref: inputRef, name: "Test Suite Name", prompt: "Unique Identifier for Test suite i.e Person_suite", value: suiteName, placeholder: "Suite Name", update: (value) => setSuiteName(value ?? ''), errorMessage: validateTestableId(suiteName, undefined) }), _jsx(PanelFormTextField, { name: "Test Name", prompt: "Unique Identifier for first test in suite", placeholder: "Test Name", value: testName, update: (value) => setTestName(value ?? ''), errorMessage: validateTestableId(testName, undefined) })] }), _jsxs(ModalFooter, { children: [_jsx(ModalFooterButton, { disabled: !isValid, title: !isValid
                                ? 'Suite Name and Test Name Required'
                                : 'Create Test Suite', onClick: create, text: "Create" }), _jsx(ModalFooterButton, { onClick: close, text: "Close", type: "secondary" })] })] }) }));
});
// ──────────────────────────────────────────────────────────────────────────────
// Main Testing Tab — suite tabs at top, suite editor below
// ──────────────────────────────────────────────────────────────────────────────
export const FunctionTestableEditor = observer((props) => {
    const { functionTestableState } = props;
    const suites = functionTestableState.function.tests;
    const functionEditorState = functionTestableState.functionEditorState;
    const isReadOnly = functionEditorState.isReadOnly;
    const selectedSuiteState = functionTestableState.selectedTestSuite;
    useEffect(() => {
        functionTestableState.init();
    }, [functionTestableState]);
    const addSuite = () => {
        functionTestableState.setCreateSuite(true);
    };
    const changeSuite = (suite) => {
        functionTestableState.changeSuite(suite);
    };
    const runSuites = () => {
        functionTestableState.runTestable();
    };
    const renameTestingComponent = (val) => {
        functionTestableState.renameTestableComponent(val);
    };
    useApplicationNavigationContext(LEGEND_STUDIO_APPLICATION_NAVIGATION_CONTEXT_KEY.FUNCTION_EDITOR_TEST);
    return (_jsxs(Panel, { className: "service-test-suite-editor", children: [functionTestableState.createSuiteModal && (_jsx(CreateFunctionTestSuiteModal, { functionTestableEditorState: functionTestableState })), _jsxs(PanelHeader, { children: [suites.length ? (_jsx(PanelHeader, { className: "service-test-suite-editor__header service-test-suite-editor__header--with-tabs", children: _jsx("div", { className: "uml-element-editor__tabs", children: suites.map((suite) => (_jsx("div", { onClick: () => changeSuite(suite), className: clsx('service-test-suite-editor__tab', {
                                    'service-test-suite-editor__tab--active': selectedSuiteState?.suite === suite,
                                }), children: _jsx(ContextMenu, { className: "mapping-editor__header__tab__content", content: _jsx(SuiteHeaderTabContextMenu, { functionTestableState: functionTestableState, suite: suite }), children: suite.id }) }, suite.id))) }) })) : (_jsx("div", {})), _jsxs(PanelHeaderActions, { children: [_jsx(PanelHeaderActionItem, { onClick: runSuites, title: "Run All Suites", children: _jsx(RunAllIcon, {}) }), _jsx(PanelHeaderActionItem, { onClick: addSuite, title: "Add Test Suite", children: _jsx(PlusIcon, {}) })] })] }), _jsxs(Panel, { className: "service-test-suite-editor", children: [selectedSuiteState && (_jsx(FunctionTestSuiteEditor, { functionTestSuiteState: selectedSuiteState })), !suites.length && (_jsx(BlankPanelPlaceholder, { text: "Add Test Suite", onClick: addSuite, clickActionType: "add", tooltipText: "Click to add test suite" })), functionTestableState.testableComponentToRename && (_jsx(RenameModal, { val: functionTestableState.testableComponentToRename.id, isReadOnly: isReadOnly, showModal: true, closeModal: () => functionTestableState.setRenameComponent(undefined), setValue: (val) => renameTestingComponent(val), errorMessageFunc: (_val) => validateTestableId(_val, undefined) }))] })] }));
});
//# sourceMappingURL=FunctionTestableEditor.js.map