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 { BlankPanelPlaceholder, clsx, ContextMenu, CustomSelectorInput, Dialog, MenuContent, MenuContentItem, Modal, ModalBody, ModalFooter, ModalFooterButton, ModalHeader, PanelFormBooleanField, PlusIcon, ResizablePanel, ResizablePanelGroup, ResizablePanelSplitter, ResizablePanelSplitterLine, UploadIcon, } from '@finos/legend-art';
import { getAllTablesFromDatabase, RelationalCSVDataTable, } from '@finos/legend-graph';
import { observer } from 'mobx-react-lite';
import { forwardRef, useState } from 'react';
import { CODE_EDITOR_LANGUAGE } from '@finos/legend-code-editor';
import { CodeEditor } from '@finos/legend-lego/code-editor';
import { LEGEND_STUDIO_APPLICATION_NAVIGATION_CONTEXT_KEY } from '../../../../__lib__/LegendStudioApplicationNavigationContext.js';
import { useApplicationNavigationContext } from '@finos/legend-application';
import { relationalData_addTable, relationalData_setTableName, relationalData_setTableSchemaName, } from '../../../../stores/graph-modifier/DSL_Data_GraphModifierHelper.js';
import { createMockDataForMappingElementSource } from '../../../../stores/editor/utils/MockDataUtils.js';
const RelationalTableIdentifierEditor = observer((props) => {
    const { isReadOnly, dataState } = props;
    const applicationStore = dataState.editorStore.applicationStore;
    const resolvedDb = dataState.database;
    const existingDataTable = dataState.tableToEdit;
    // table
    const [schemaName, setSchemaName] = useState(existingDataTable?.schema);
    const [tableName, setTableName] = useState(existingDataTable?.table);
    // selectors if db provided
    const tables = resolvedDb
        ? getAllTablesFromDatabase(resolvedDb)
        : undefined;
    const [dbTable, setDbTable] = useState(tables?.[0]);
    const [includeBare, setIncludeBare] = useState(true);
    const showFullPath = resolvedDb && resolvedDb.schemas.length > 2;
    const tableOptions = tables?.map((_t) => ({
        label: showFullPath ? `${_t.schema.name}.${_t.name}` : `${_t.name}`,
        value: _t,
    })) ?? [];
    const onTableChange = (val) => {
        setDbTable(val?.value);
    };
    const selectedTable = dbTable
        ? {
            label: showFullPath
                ? `${dbTable.schema.name}.${dbTable.name}`
                : `${dbTable.name}`,
            value: dbTable,
        }
        : undefined;
    const closeModal = () => dataState.closeModal();
    const changeSchemaValue = (event) => {
        setSchemaName(event.target.value);
    };
    const changeTableValue = (event) => {
        setTableName(event.target.value);
    };
    const toggleIncludeBare = () => {
        setIncludeBare(!includeBare);
    };
    const useSelector = resolvedDb && !existingDataTable;
    const isDisabled = useSelector ? !dbTable : !(schemaName && tableName);
    const handleSubmit = () => {
        const newTable = new RelationalCSVDataTable();
        newTable.values = '';
        const editTable = existingDataTable ?? newTable;
        const _schemaName = useSelector ? dbTable?.schema.name : schemaName;
        const _name = useSelector ? dbTable?.name : tableName;
        relationalData_setTableSchemaName(editTable, _schemaName ?? '');
        relationalData_setTableName(editTable, _name ?? '');
        if (!existingDataTable && dbTable && includeBare) {
            editTable.values = createMockDataForMappingElementSource(dbTable, dataState.editorStore);
        }
        if (!existingDataTable) {
            relationalData_addTable(dataState.embeddedData, editTable);
            dataState.changeSelectedTable(editTable);
        }
        closeModal();
    };
    return (_jsx(Dialog, { open: dataState.showTableIdentifierModal, onClose: closeModal, classes: { container: 'search-modal__container' }, slotProps: {
            paper: {
                classes: { root: 'search-modal__inner-container' },
            },
        }, children: _jsxs("form", { onSubmit: (event) => {
                event.preventDefault();
                handleSubmit();
                closeModal();
            }, className: "modal modal--dark search-modal", children: [_jsx("div", { className: "modal__title", children: existingDataTable
                        ? 'Rename Relational Data Table'
                        : 'Add Relational Data Table' }), _jsx("div", { className: "relational-data-editor__identifier", children: resolvedDb && !existingDataTable ? (_jsxs(_Fragment, { children: [_jsxs("div", { className: "panel__content__form__section", children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Table" }), _jsx("div", { className: "explorer__new-element-modal__driver", children: _jsx(CustomSelectorInput, { className: "explorer__new-element-modal__driver__dropdown", options: tableOptions, onChange: onTableChange, value: selectedTable, isClearable: false, darkMode: !applicationStore.layoutService
                                                .TEMPORARY__isLightColorThemeEnabled }) })] }), _jsx(PanelFormBooleanField, { isReadOnly: isReadOnly, value: includeBare, name: "Include Columns and First Row", prompt: "Will include table columns and first row using table definition", update: toggleIncludeBare })] })) : (_jsxs(_Fragment, { children: [_jsx("div", { className: "relational-data-editor__identifier__values", children: _jsx("input", { className: "panel__content__form__section__input", disabled: isReadOnly, placeholder: "schemaName", value: schemaName, onChange: changeSchemaValue }) }), _jsx("div", { className: "relational-data-editor__identifier__values", children: _jsx("input", { className: "relational-data-editor__identifier__values panel__content__form__section__input", disabled: isReadOnly, placeholder: "tableName", value: tableName, onChange: changeTableValue }) })] })) }), _jsx("div", { className: "search-modal__actions", children: _jsx("button", { className: "btn btn--dark", disabled: isDisabled || isReadOnly, children: existingDataTable ? 'Rename' : 'Add' }) })] }) }));
});
const RelationalCSVTableContextMenu = observer(forwardRef(function TestContainerContextMenu(props, ref) {
    const { dataState, table } = props;
    const rename = () => dataState.openIdentifierModal(table);
    const remove = () => dataState.deleteTable(table);
    return (_jsxs(MenuContent, { ref: ref, children: [_jsx(MenuContentItem, { onClick: rename, children: "Rename" }), _jsx(MenuContentItem, { onClick: remove, children: "Delete" })] }));
}));
const ImportModal = observer((props) => {
    const { isReadOnly, dataState } = props;
    const applicationStore = dataState.editorStore.applicationStore;
    const [csv, setCSV] = useState('');
    const closeModal = () => dataState.closeCSVModal();
    const importVal = () => {
        dataState.importCSV(csv);
        setCSV('');
        closeModal();
    };
    const changeCSV = (event) => {
        setCSV(event.target.value);
    };
    return (_jsx(Dialog, { open: dataState.showImportCSVModal, onClose: closeModal, classes: { container: 'search-modal__container' }, slotProps: {
            paper: {
                classes: { root: 'search-modal__inner-container' },
            },
        }, children: _jsxs(Modal, { darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled, className: "relational-data-editor__import", children: [_jsx(ModalHeader, { title: "Import CSV" }), _jsx(ModalBody, { children: _jsx("textarea", { className: "relational-data-editor__import__textarea", spellCheck: false, placeholder: "CSV Text", value: csv, onChange: changeCSV, disabled: isReadOnly }) }), _jsx(ModalFooter, { children: _jsx(ModalFooterButton, { text: "Import", title: "Create new query", onClick: importVal }) })] }) }));
});
export const RelationalCSVDataEditor = observer((props) => {
    const { dataState, isReadOnly } = props;
    const currentTableState = dataState.selectedTable;
    const openIdentifierModal = () => dataState.openIdentifierModal();
    const changeSelectedTable = (table) => {
        dataState.changeSelectedTable(table);
    };
    const updateTableValues = (val) => {
        currentTableState?.updateTableValues(val);
    };
    const [selectedTableFromContextMenu, setSelectedTableFromContextMenu] = useState(undefined);
    const onContextMenuOpen = (table) => setSelectedTableFromContextMenu(table);
    const onContextMenuClose = () => setSelectedTableFromContextMenu(undefined);
    const isTableActive = (table) => currentTableState?.table === table;
    const showCSVModal = () => dataState.setShowImportCsvModal(true);
    useApplicationNavigationContext(LEGEND_STUDIO_APPLICATION_NAVIGATION_CONTEXT_KEY.EMBEDDED_DATA_RELATIONAL_EDITOR);
    return (_jsxs(ResizablePanelGroup, { orientation: "vertical", children: [_jsx(ResizablePanel, { minSize: 30, size: 300, children: _jsxs("div", { className: "relational-data-editor", children: [_jsxs("div", { className: "relational-data-editor__header", children: [_jsx("div", { className: "relational-data-editor__header__title", children: _jsx("div", { className: "relational-data-editor__header__title__label", children: "Relational Table Explorer" }) }), _jsxs("div", { className: "relational-data-editor__header__actions", children: [_jsx("button", { className: "schema-set-panel__header__action", onClick: showCSVModal, disabled: isReadOnly, tabIndex: -1, title: "Import CSV", children: _jsx(UploadIcon, {}) }), _jsx("button", { className: "relational-data-editor__header__action", onClick: openIdentifierModal, disabled: isReadOnly, tabIndex: -1, title: "Add Relational Table Data", children: _jsx(PlusIcon, {}) })] })] }), _jsx(MenuContent, { className: "relational-data-editor__content", children: dataState.embeddedData.tables.map((_table) => (_jsx(ContextMenu, { className: clsx('relational-data-editor-explorer__item', {
                                    'relational-data-editor-explorer__item--selected-from-context-menu': !isTableActive(_table) &&
                                        selectedTableFromContextMenu ===
                                            currentTableState?.table,
                                }, {
                                    'relational-data-editor-explorer__item--active': isTableActive(_table),
                                }), disabled: isReadOnly, content: _jsx(RelationalCSVTableContextMenu, { dataState: dataState, table: _table }), menuProps: { elevation: 7 }, onOpen: () => onContextMenuOpen(_table), onClose: () => onContextMenuClose(), children: _jsx("button", { className: clsx('relational-data-editor-explorer__item__label'), onClick: () => changeSelectedTable(_table), tabIndex: -1, children: _jsx("div", { className: "relational-data-editor-explorer__item__label__text", children: `${_table.schema}.${_table.table}` }) }) }, `${_table.table}.${_table.schema}`))) })] }) }), _jsx(ResizablePanelSplitter, { children: _jsx(ResizablePanelSplitterLine, { color: "var(--color-dark-grey-200)" }) }), _jsx(ResizablePanel, { children: _jsxs("div", { className: "relational-data-editor", children: [_jsx("div", { className: "relational-data-editor__header", children: _jsx("div", { className: "relational-data-editor__header__title", children: _jsx("div", { className: "relational-data-editor__header__title__label", children: "CSV Values" }) }) }), _jsxs("div", { className: "relational-data-editor__content", children: [currentTableState && (_jsx("div", { className: "relational-data-editor__values", children: _jsx(CodeEditor, { inputValue: currentTableState.table.values, updateInput: updateTableValues, isReadOnly: isReadOnly, language: CODE_EDITOR_LANGUAGE.TEXT }) })), !currentTableState && (_jsx(BlankPanelPlaceholder, { onClick: () => openIdentifierModal(), text: "Add a relational data table", clickActionType: "add", tooltipText: "Click to add new relational data table" })), dataState.showTableIdentifierModal && (_jsx(RelationalTableIdentifierEditor, { dataState: dataState, isReadOnly: isReadOnly })), dataState.showImportCSVModal && (_jsx(ImportModal, { dataState: dataState, isReadOnly: isReadOnly }))] })] }) })] }));
});
//# sourceMappingURL=RelationalCSVDataEditor.js.map