import { jsx as _jsx, jsxs as _jsxs } 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 { ResizablePanelGroup, ResizablePanel, Panel, BaseStepper, PanelContent, Modal, ModalBody, InputWithInlineValidation, PanelHeader, PanelLoadingIndicator, ResizablePanelSplitter, EyeIcon, BlankPanelContent, } from '@finos/legend-art';
import { observer } from 'mobx-react-lite';
import { useEffect, useMemo } from 'react';
import { RelationalConnectionGeneralEditor } from '../connection-editor/RelationalDatabaseConnectionEditor.js';
import { flowResult } from 'mobx';
import { useApplicationStore } from '@finos/legend-application';
import { DatabaseBuilderModalContent } from '../connection-editor/DatabaseBuilderWizard.js';
import { debounce, guaranteeNonNullable } from '@finos/legend-shared';
import { CODE_EDITOR_LANGUAGE } from '@finos/legend-code-editor';
import { CodeEditor } from '@finos/legend-lego/code-editor';
import { DatabaseModelPackageInput, DatabaseModelPreviewEditor, } from '../connection-editor/DatabaseModelBuilder.js';
import { ConnectionValueStepperState, DatabaseBuilderStepperState, DatabaseGrammarEditorStepperState, DatabaseModelBuilderStepperState, QUERY_CONNECTION_WORKFLOW_STEPS, QueryConnectionConfirmationAndGrammarEditorStepperState, } from '../../../../stores/editor/editor-state/end-to-end-workflow-state/QueryConnectionEndToEndWorkflowEditorState.js';
export const QueryConnectionRelationalConnectionEditor = observer((props) => {
    const { queryConnectionEndToEndWorkflowState, connectionValueStepperState, } = props;
    const elementAlreadyExistsMessage = queryConnectionEndToEndWorkflowState.editorStore.graphManagerState.graph.allElements
        .map((s) => s.path)
        .includes(connectionValueStepperState.targetConnectionPath)
        ? 'Element with same path already exists'
        : undefined;
    const onTargetPathChange = (event) => {
        connectionValueStepperState.setTargetConnectionPath(event.target.value);
    };
    return (_jsxs(Panel, { className: "query-connection-workflow-panel query-connection-relational-connection-editor", children: [_jsx(PanelHeader, { title: "build a connection" }), _jsx(PanelContent, { children: _jsxs("div", { className: "query-connection-relational-connection-editor__connection-builder", children: [_jsxs("div", { className: "panel__content__form__section query-connection-relational-connection-editor__connection-builder__path", children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Target Connection Path" }), _jsx(InputWithInlineValidation, { className: "panel__content__form__section__input", spellCheck: false, onChange: onTargetPathChange, value: connectionValueStepperState.targetConnectionPath, error: elementAlreadyExistsMessage, showEditableIcon: true })] }), _jsx("div", { className: "query-connection-relational-connection-editor__editor", children: _jsx(RelationalConnectionGeneralEditor, { connectionValueState: connectionValueStepperState.connectionValueState, isReadOnly: false, hideHeader: true }) })] }) })] }));
});
export const QueryConnectionDatabaseBuilderEditor = observer((props) => {
    const { databaseBuilderState } = props;
    const applicationStore = useApplicationStore();
    const preview = applicationStore.guardUnhandledError(() => flowResult(databaseBuilderState.previewDatabaseModel()));
    return (_jsxs(Panel, { className: "query-connection-workflow-panel query-connection-database-builder-editor", children: [_jsxs("div", { className: "query-connection-workflow-panel query-connection-database-builder-editor__header", children: [_jsx(PanelHeader, { title: "Database Builder" }), _jsxs("button", { className: "query-connection-workflow-panel query-connection-database-builder-editor__header__action", onClick: preview, title: "Preview database...", children: [_jsx(EyeIcon, { className: "query-connection-database-builder-editor__header__action__icon" }), _jsx("div", { className: "query-connection-database-builder-editor__header__action__label", children: "Preview" })] })] }), _jsx(Modal, { darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled, className: "query-connection-database-builder-editor__modal", children: _jsx("div", { className: "query-connection-database-builder-editor__modal__content", children: _jsx(DatabaseBuilderModalContent, { databaseBuilderState: databaseBuilderState }) }) })] }));
});
export const QueryConnectionDatabaseGrammarEditor = observer((props) => {
    const { queryConnectionEndToEndWorkflowState, databaseGrammarEditorStepperState, } = props;
    const applicationStore = useApplicationStore();
    const compile = () => {
        flowResult(databaseGrammarEditorStepperState.compileDatabaseGrammarCode()).catch(applicationStore.alertUnhandledError);
    };
    const updateDatabaseGrammar = (val) => {
        queryConnectionEndToEndWorkflowState.setDatabaseGrammarCode(val);
    };
    return (_jsxs(Panel, { className: "query-connection-workflow-panel query-connection-database-builder-editor", children: [_jsxs("div", { className: "query-connection-workflow-panel query-connection-database-builder-editor__header", children: [_jsx(PanelHeader, { title: "Database Editor" }), _jsx("button", { className: "query-connection-workflow-panel query-connection-database-builder-editor__header__action", onClick: compile, title: "Compile database model...", children: "Compile" })] }), _jsx(PanelLoadingIndicator, { isLoading: databaseGrammarEditorStepperState.isCompilingGrammarCode
                    .isInProgress }), _jsx("div", { className: "panel__content__form__section__header__prompt query-connection-database-builder-editor__prompt", children: "Joins could be added manually and please be aware that only one database is supported in this flow" }), _jsx("div", { className: "query-connection-database-builder-editor__editor", children: _jsx(CodeEditor, { inputValue: queryConnectionEndToEndWorkflowState.databaseGrammarCode, updateInput: updateDatabaseGrammar, language: CODE_EDITOR_LANGUAGE.PURE, error: queryConnectionEndToEndWorkflowState.compileError }) })] }));
});
export const QueryConnectionModelsEditor = observer((props) => {
    const { databaseModelBuilderStepperState, queryConnectionEndToEndWorkflowState, } = props;
    const applicationStore = useApplicationStore();
    const runtimeElementAlreadyExistsMessage = queryConnectionEndToEndWorkflowState.editorStore.graphManagerState.graph.allElements
        .map((s) => s.path)
        .includes(queryConnectionEndToEndWorkflowState.targetRuntimePath)
        ? 'Element with same path already exists or must contain ::'
        : undefined;
    const debouncedRegenerateRuntime = useMemo(() => debounce((val) => {
        if (val !== '') {
            queryConnectionEndToEndWorkflowState.updateRuntime(val);
        }
    }, 500), [queryConnectionEndToEndWorkflowState]);
    const changeTargetRuntimePackage = (event) => {
        queryConnectionEndToEndWorkflowState.setTargetRuntimePath(event.target.value);
        debouncedRegenerateRuntime(event.target.value);
    };
    useEffect(() => {
        flowResult(databaseModelBuilderStepperState.databaseModelBuilderState.previewDatabaseModels())
            .then(() => databaseModelBuilderStepperState.updateGraphWithModels(guaranteeNonNullable(databaseModelBuilderStepperState.databaseModelBuilderState
            .entities)))
            .catch(applicationStore.alertUnhandledError);
    }, [
        applicationStore,
        databaseModelBuilderStepperState,
        databaseModelBuilderStepperState.databaseModelBuilderState,
        databaseModelBuilderStepperState.databaseModelBuilderState.targetPackage,
        queryConnectionEndToEndWorkflowState,
    ]);
    return (_jsxs(Panel, { className: "query-connection-workflow-panel query-connection-database-builder-editor", children: [_jsx("div", { className: "query-connection-workflow-panel query-connection-database-builder-editor__header", children: _jsx(PanelHeader, { title: "Model Builder" }) }), _jsx(Modal, { darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled, className: "query-connection-connection-model-editor__modal", children: _jsx("div", { className: "query-connection-connection-model-editor__modal", children: _jsx(ModalBody, { className: "database-builder__content", children: _jsxs(ResizablePanelGroup, { orientation: "vertical", children: [_jsx(ResizablePanel, { size: 450, children: _jsxs("div", { className: "database-builder__config", children: [_jsx(PanelHeader, { title: "schema explorer" }), _jsxs(PanelContent, { className: "database-builder__config__content", children: [_jsx(DatabaseModelPackageInput, { databaseModelBuilderState: databaseModelBuilderStepperState.databaseModelBuilderState }), _jsxs("div", { className: "panel__content__form__section", children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Target Runtime Path" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Target path for runtime" }), _jsx(InputWithInlineValidation, { className: "query-builder__variables__variable__name__input input-group__input", spellCheck: false, value: queryConnectionEndToEndWorkflowState.targetRuntimePath, onChange: changeTargetRuntimePackage, placeholder: "Target Runtime path", error: runtimeElementAlreadyExistsMessage, showEditableIcon: true })] })] })] }) }), _jsx(ResizablePanelSplitter, {}), _jsx(ResizablePanel, { children: _jsx(DatabaseModelPreviewEditor, { databaseModelBuilderState: databaseModelBuilderStepperState.databaseModelBuilderState, grammarCode: databaseModelBuilderStepperState.databaseModelBuilderState.generatedGrammarCode.concat(queryConnectionEndToEndWorkflowState.runtimeGrammarCode) }) })] }) }) }) })] }));
});
export const QueryConnectionConfirmationAndGrammarEditor = observer((props) => {
    const { queryConnectionEndToEndWorkflowState, queryConnectionConfirmationAndGrammarEditorStepperState, } = props;
    const applicationStore = useApplicationStore();
    const compile = () => {
        flowResult(queryConnectionConfirmationAndGrammarEditorStepperState.compile()).catch(applicationStore.alertUnhandledError);
    };
    const updateInput = (val) => {
        queryConnectionEndToEndWorkflowState.setFinalGrammarCode(val);
    };
    return (_jsxs(Panel, { className: "query-connection-workflow-panel query-connection-database-builder-editor", children: [_jsxs("div", { className: "query-connection-workflow-panel query-connection-database-builder-editor__header", children: [_jsx(PanelHeader, { title: "Database Editor" }), _jsx("button", { className: "query-connection-workflow-panel query-connection-database-builder-editor__header__action", onClick: compile, title: "Compile model...", children: "Compile" })] }), _jsx(PanelLoadingIndicator, { isLoading: queryConnectionConfirmationAndGrammarEditorStepperState
                    .isCompilingCode.isInProgress }), _jsx("div", { className: "panel__content__form__section__header__prompt query-connection-database-builder-editor__prompt", children: "Please confirm models below will be added to the project and click query to open query builder" }), _jsx("div", { className: "query-connection-database-builder-editor__editor", children: _jsx(CodeEditor, { inputValue: queryConnectionEndToEndWorkflowState.finalGrammarCode, updateInput: updateInput, language: CODE_EDITOR_LANGUAGE.PURE, error: queryConnectionEndToEndWorkflowState.compileError }) })] }));
});
export const QueryConnectionWorflowEditor = observer((props) => {
    const { connectionToQueryWorkflowState } = props;
    const applicationStore = useApplicationStore();
    const stepLabel = connectionToQueryWorkflowState.activeStepToStepLabel.get(connectionToQueryWorkflowState.activeStep);
    const increaseActiveStep = () => {
        if (connectionToQueryWorkflowState.isValid) {
            connectionToQueryWorkflowState.setActiveStep(connectionToQueryWorkflowState.activeStep + 1);
        }
    };
    const handleNext = () => {
        if (stepLabel) {
            flowResult(connectionToQueryWorkflowState.activeStepToBaseStepperState
                .get(stepLabel)
                ?.handleNext())
                .then(() => increaseActiveStep())
                .catch(applicationStore.alertUnhandledError);
        }
    };
    const handleBack = () => {
        connectionToQueryWorkflowState.setCompileError(undefined);
        connectionToQueryWorkflowState.setActiveStep(connectionToQueryWorkflowState.activeStep - 1);
    };
    const renderStepContent = () => {
        if (stepLabel) {
            const currentState = connectionToQueryWorkflowState.activeStepToBaseStepperState.get(stepLabel);
            if (currentState instanceof ConnectionValueStepperState) {
                return (_jsx(QueryConnectionRelationalConnectionEditor, { queryConnectionEndToEndWorkflowState: currentState.workflowEditorState, connectionValueStepperState: currentState }));
            }
            else if (currentState instanceof DatabaseBuilderStepperState) {
                return (_jsx(QueryConnectionDatabaseBuilderEditor, { databaseBuilderState: currentState.databaseBuilderWizardState }));
            }
            else if (currentState instanceof DatabaseGrammarEditorStepperState) {
                return (_jsx(QueryConnectionDatabaseGrammarEditor, { queryConnectionEndToEndWorkflowState: currentState.workflowEditorState, databaseGrammarEditorStepperState: currentState }));
            }
            else if (currentState instanceof DatabaseModelBuilderStepperState) {
                return (_jsx(QueryConnectionModelsEditor, { databaseModelBuilderStepperState: currentState, queryConnectionEndToEndWorkflowState: currentState.workflowEditorState }));
            }
            else if (currentState instanceof
                QueryConnectionConfirmationAndGrammarEditorStepperState) {
                return (_jsx(QueryConnectionConfirmationAndGrammarEditor, { queryConnectionEndToEndWorkflowState: currentState.workflowEditorState, queryConnectionConfirmationAndGrammarEditorStepperState: currentState }));
            }
        }
        return _jsx(BlankPanelContent, { children: " " });
    };
    return (_jsx("div", { children: _jsxs(Panel, { children: [_jsxs(PanelContent, { className: "test-runner-panel__result", children: [_jsx(BaseStepper, { steps: Object.values(QUERY_CONNECTION_WORKFLOW_STEPS), activeStep: connectionToQueryWorkflowState.activeStep }), _jsx(PanelContent, { children: _jsx("div", { className: "query-connection-workflow__content", children: renderStepContent() }) })] }), _jsxs("div", { className: "query-connection-workflow__actions", children: [_jsx("button", { className: "query-connection-workflow__actions__action-btn", disabled: connectionToQueryWorkflowState.activeStep === 0, onClick: handleBack, title: "Go to previous step...", children: "Back" }), _jsx("button", { className: "query-connection-workflow__actions__action-btn query-connection-workflow__actions__action-btn--primary", onClick: handleNext, children: connectionToQueryWorkflowState.activeStep ===
                                Object.values(QUERY_CONNECTION_WORKFLOW_STEPS).length - 1
                                ? 'Import And Query'
                                : 'Next' })] })] }) }));
});
//# sourceMappingURL=ConnectionToQueryWorkflowEditor.js.map