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 { observer } from 'mobx-react-lite';
import { ResizablePanelGroup, ResizablePanel, ResizablePanelSplitter, CustomSelectorInput, createFilter, PURE_ConnectionIcon, BlankPanelPlaceholder, PanelDropZone, PanelLoadingIndicator, PURE_DatabaseIcon, SyncIcon, } from '@finos/legend-art';
import { useCallback, useEffect, useRef } from 'react';
import { useApplicationStore, useConditionedApplicationNavigationContext, } from '@finos/legend-application';
import { flowResult } from 'mobx';
import { PackageableConnection, RelationalDatabaseConnection, } from '@finos/legend-graph';
import { LEGEND_STUDIO_APPLICATION_NAVIGATION_CONTEXT_KEY } from '../../../__lib__/LegendStudioApplicationNavigationContext.js';
import { useEditorStore } from '../EditorStoreProvider.js';
import { PANEL_MODE } from '../../../stores/editor/EditorConfig.js';
import { useDrag, useDrop } from 'react-dnd';
import { CORE_DND_TYPE, } from '../../../stores/editor/utils/DnDUtils.js';
import { DatabaseSchemaExplorer, DatabaseSchemaExplorerTreeNodeContainer, } from '../editor-group/connection-editor/DatabaseSchemaExplorer.js';
import { DatabaseSchemaExplorerTreeTableNodeData } from '../../../stores/editor/editor-state/element-editor-state/connection/DatabaseBuilderState.js';
import { buildRelationalDatabaseConnectionOption, } from '../editor-group/connection-editor/RelationalDatabaseConnectionEditor.js';
import { SQLPlaygroundEditorResultPanel } from '@finos/legend-lego/sql-playground';
const DATABASE_NODE_DND_TYPE = 'DATABASE_NODE_DND_TYPE';
const SQLPlaygroundDatabaseSchemaExplorerTreeNodeContainer = observer((props) => {
    const { node } = props;
    const ref = useRef(null);
    const [, dragConnector] = useDrag(() => ({
        type: DATABASE_NODE_DND_TYPE,
        item: {
            text: node instanceof DatabaseSchemaExplorerTreeTableNodeData
                ? `${node.owner.name}.${node.label}`
                : node.label,
        },
    }), [node]);
    dragConnector(ref);
    return _jsx(DatabaseSchemaExplorerTreeNodeContainer, { ...props, ref: ref });
});
export const SQLPlaygroundPanel = observer(() => {
    const editorStore = useEditorStore();
    const playgroundState = editorStore.studioSqlPlaygroundState;
    const applicationStore = useApplicationStore();
    // connection
    const connectionSelectorRef = useRef(null);
    const connectionFilterOption = createFilter({
        ignoreCase: true,
        ignoreAccents: false,
        stringify: (option) => option.data.value.path,
    });
    const connectionOptions = editorStore.graphManagerState.usableConnections
        .filter((connection) => connection.connectionValue instanceof RelationalDatabaseConnection)
        .map(buildRelationalDatabaseConnectionOption);
    const selectedConnectionOption = playgroundState.connection
        ? buildRelationalDatabaseConnectionOption(playgroundState.connection)
        : null;
    const changeConnection = (val) => {
        if (val.value === playgroundState.connection) {
            return;
        }
        playgroundState.setConnection(val.value);
    };
    const onPickConnection = () => {
        editorStore.setQuickInputState({
            title: 'Connection picker',
            placeholder: 'Select a connection...',
            options: connectionOptions,
            getSearchValue: (option) => option.value.path,
            onSelect: changeConnection,
        });
    };
    const handleConnectionDrop = useCallback((item) => {
        if (item.data.packageableElement instanceof PackageableConnection) {
            if (item.data.packageableElement.connectionValue instanceof
                RelationalDatabaseConnection) {
                playgroundState.setConnection(item.data.packageableElement);
            }
            else {
                applicationStore.notificationService.notifyWarning(`Can't use SQL playground with non-relational database connection`);
            }
        }
    }, [playgroundState, applicationStore]);
    const [{ isConnectionDragOver }, dropConnector] = useDrop(() => ({
        accept: CORE_DND_TYPE.PROJECT_EXPLORER_CONNECTION,
        drop: (item) => handleConnectionDrop(item),
        collect: (monitor) => ({
            isConnectionDragOver: monitor.isOver({ shallow: true }),
        }),
    }), [handleConnectionDrop]);
    const updateDatabase = () => {
        if (playgroundState.schemaExplorerState) {
            flowResult(playgroundState.schemaExplorerState.updateDatabase()).catch(applicationStore.alertUnhandledError);
        }
    };
    useEffect(() => {
        if (playgroundState.schemaExplorerState) {
            flowResult(playgroundState.schemaExplorerState.fetchDatabaseMetadata()).catch(applicationStore.alertUnhandledError);
        }
    }, [playgroundState, applicationStore, playgroundState.schemaExplorerState]);
    useEffect(() => {
        playgroundState.fetchSchemaMetaData();
    }, [playgroundState]);
    useConditionedApplicationNavigationContext(LEGEND_STUDIO_APPLICATION_NAVIGATION_CONTEXT_KEY.SQL_PLAYGROUND, editorStore.activePanelMode === PANEL_MODE.SQL_PLAYGROUND);
    return (_jsx(PanelDropZone, { isDragOver: isConnectionDragOver, dropTargetConnector: dropConnector, children: _jsxs("div", { className: "sql-playground", children: [playgroundState.connection && (_jsxs(ResizablePanelGroup, { orientation: "vertical", children: [_jsx(ResizablePanel, { size: 300, children: _jsxs("div", { className: "sql-playground__config", children: [_jsxs("div", { className: "sql-playground__config__setup", children: [_jsxs("div", { className: "sql-playground__config__connection-selector", children: [_jsx("div", { className: "sql-playground__config__connection-selector__icon", children: _jsx(PURE_ConnectionIcon, {}) }), _jsx(CustomSelectorInput, { inputRef: connectionSelectorRef, className: "sql-playground__config__connection-selector__input", options: connectionOptions, onChange: changeConnection, value: selectedConnectionOption, darkMode: !applicationStore.layoutService
                                                            .TEMPORARY__isLightColorThemeEnabled, placeholder: "Choose a connection...", filterOption: connectionFilterOption })] }), _jsxs("div", { className: "sql-playground__config__database-selector", children: [_jsx("div", { className: "sql-playground__config__database-selector__icon", children: _jsx(PURE_DatabaseIcon, {}) }), _jsx(CustomSelectorInput, { inputRef: connectionSelectorRef, className: "sql-playground__config__database-selector__input", options: connectionOptions, onChange: changeConnection, value: selectedConnectionOption, darkMode: !applicationStore.layoutService
                                                            .TEMPORARY__isLightColorThemeEnabled, placeholder: "Choose a connection...", filterOption: connectionFilterOption }), _jsx("button", { className: "sql-playground__config__database-selector__update-btn btn--sm btn--dark", disabled: !playgroundState.database, onClick: updateDatabase, title: "Update database", children: _jsx(SyncIcon, {}) })] })] }), _jsxs("div", { className: "sql-playground__config__schema-explorer", children: [_jsx(PanelLoadingIndicator, { isLoading: Boolean(playgroundState.schemaExplorerState?.isGeneratingDatabase) }), playgroundState.schemaExplorerState?.treeData && (_jsx(DatabaseSchemaExplorer, { treeData: playgroundState.schemaExplorerState.treeData, schemaExplorerState: playgroundState.schemaExplorerState, treeNodeContainerComponent: SQLPlaygroundDatabaseSchemaExplorerTreeNodeContainer }))] })] }) }), _jsx(ResizablePanelSplitter, {}), _jsx(ResizablePanel, { children: _jsx("div", { className: "panel sql-playground__sql-editor", children: _jsx(SQLPlaygroundEditorResultPanel, { playgroundState: playgroundState, advancedMode: true, enableDarkMode: true }) }) })] })), !playgroundState.connection && (_jsx(BlankPanelPlaceholder, { onClick: onPickConnection, clickActionType: "add", text: "Pick a connection to start", tooltipText: "Drop a connection to start...", isDropZoneActive: isConnectionDragOver }))] }) }));
});
//# sourceMappingURL=SQLPlaygroundPanel.js.map