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 { useEditorStore } from '../../EditorStoreProvider.js';
import { DATA_PRODUCT_TAB, DATA_PRODUCT_TYPE, DataProductEditorState, generateUrlToDeployOnOpen, LakehouseAccessPointState, ModelAccessPointGroupState, } from '../../../../stores/editor/editor-state/element-editor-state/dataProduct/DataProductEditorState.js';
import { BugIcon, BuildingIcon, CaretDownIcon, Checkbox, CloseEyeIcon, clsx, compressImage, ControlledDropdownMenu, CustomSelectorInput, Dialog, DragPreviewLayer, ErrorWarnIcon, EyeIcon, GroupWorkIcon, HomeIcon, IconSelectorGrid, IconSelectorIcons, InfoCircleIcon, ListEditor, LockIcon, MenuContent, MenuContentItem, Modal, ModalBody, ModalFooter, ModalFooterButton, ModalHeader, ModalTitle, PanelContent, PanelDnDEntry, PanelEntryDragHandle, PanelFormTextField, PanelHeader, PanelHeaderActionItem, PanelHeaderActions, PencilEditIcon, PlusIcon, QuestionCircleIcon, ResizablePanel, ResizablePanelGroup, ResizablePanelSplitter, RocketIcon, Switch, TimesIcon, Tooltip, UploadIcon, useDragPreviewLayer, WarningIcon, LongArrowRightIcon, PURE_MappingIcon, GitBranchIcon, ListIcon, PanelLoadingIndicator, GearSuggestIcon, } from '@finos/legend-art';
import { useCallback, useEffect, useRef, useState, } from 'react';
import { filterByType, guaranteeType, UserSearchService, } from '@finos/legend-shared';
import { InlineLambdaEditor, LineageViewer } from '@finos/legend-query-builder';
import { action, autorun, flowResult } from 'mobx';
import { useAuth } from 'react-oidc-context';
import { CODE_EDITOR_LANGUAGE } from '@finos/legend-code-editor';
import { CodeEditor } from '@finos/legend-lego/code-editor';
import { DataProductEmbeddedImageIcon, DataProductLibraryIcon, Email, LakehouseTargetEnv, StereotypeExplicitReference, V1_DataProduct, V1_DataProductIconLibraryId, V1_PureGraphManager, V1_RemoteEngine, validate_PureExecutionMapping, InternalDataProductType, ExternalDataProductType, DataProductLink, observer_DataProductLink, DataProduct_Region, DataProduct_DeliveryFrequency, } from '@finos/legend-graph';
import { accessPoint_setClassification, accessPoint_setReproducible, accessPointGroup_setDescription, accessPointGroup_setName, dataProduct_setDescription, dataProduct_setIcon, dataProduct_setSupportInfoIfAbsent, dataProduct_setTitle, supportInfo_addEmail, supportInfo_deleteEmail, supportInfo_setDocumentationUrl, supportInfo_setFaqUrl, supportInfo_setLinkLabel, supportInfo_setSupportUrl, supportInfo_setWebsite, dataProduct_setType, expertise_setDescription, expertise_addId, expertise_deleteId, supportInfo_deleteExpertise, externalType_setLinkURL, externalType_setLinkLabel, accessPointGroup_setTitle, accessPoint_setDescription, accessPoint_setTitle, dataProduct_setOperationalMetadataIfAbsent, operationalMetadata_deleteCoverageRegion, operationalMetadata_addCoverageRegion, dataProductDiagram_setTitle, dataProductDiagram_setDescription, operationalMetadata_setUpdateFrequency, } from '../../../../stores/graph-modifier/DSL_DataProduct_GraphModifierHelper.js';
import { LEGEND_STUDIO_TEST_ID } from '../../../../__lib__/LegendStudioTesting.js';
import { LEGEND_STUDIO_APPLICATION_NAVIGATION_CONTEXT_KEY } from '../../../../__lib__/LegendStudioApplicationNavigationContext.js';
import { ActionAlertActionType, ActionAlertType, useApplicationNavigationContext, } from '@finos/legend-application';
import { useDrag, useDrop } from 'react-dnd';
import { annotatedElement_addStereotype, annotatedElement_deleteStereotype, } from '../../../../stores/graph-modifier/DomainGraphModifierHelper.js';
import { buildElementOption, } from '@finos/legend-lego/graph-editor';
import { DataProductViewerState, ProductViewer, } from '@finos/legend-extension-dsl-data-product';
import { RelationElementEditor } from '../data-editor/RelationElementsDataEditor.js';
export var AP_GROUP_MODAL_ERRORS;
(function (AP_GROUP_MODAL_ERRORS) {
    AP_GROUP_MODAL_ERRORS["GROUP_NAME_EMPTY"] = "Group Name is empty";
    AP_GROUP_MODAL_ERRORS["GROUP_NAME_EXISTS"] = "Group Name already exists";
    AP_GROUP_MODAL_ERRORS["GROUP_DESCRIPTION_EMPTY"] = "Group Description is empty";
    AP_GROUP_MODAL_ERRORS["AP_NAME_EMPTY"] = "Access Point Name is empty";
    AP_GROUP_MODAL_ERRORS["AP_NAME_EXISTS"] = "Access Point Name already exists";
    AP_GROUP_MODAL_ERRORS["AP_DESCRIPTION_EMPTY"] = "Access Point Description is empty";
})(AP_GROUP_MODAL_ERRORS || (AP_GROUP_MODAL_ERRORS = {}));
export const AP_EMPTY_DESC_WARNING = 'Click here to describe the data this access point produces';
const AP_DND_TYPE = 'ACCESS_POINT';
const AP_GROUP_DND_TYPE = 'ACCESS_POINT_GROUP';
const newNamePlaceholder = '';
const HoverTextArea = ({ text: text, handleMouseOver, handleMouseOut, className, }) => {
    return (_jsx("div", { onMouseOver: handleMouseOver, onMouseOut: handleMouseOut, className: clsx(className), style: { whiteSpace: 'pre-line' }, children: text }));
};
const hoverIcon = () => {
    return (_jsx("div", { "data-testid": LEGEND_STUDIO_TEST_ID.HOVER_EDIT_ICON, children: _jsx(PencilEditIcon, {}) }));
};
const AccessPointTitle = observer((props) => {
    const { accessPointState } = props;
    const accessPoint = accessPointState.accessPoint;
    const [editingName, setEditingName] = useState(accessPoint.id === newNamePlaceholder);
    const handleNameEdit = () => setEditingName(true);
    const handleNameBlur = () => {
        if (accessPoint.id !== newNamePlaceholder) {
            setEditingName(false);
            const relationElement = accessPointState.relationElementState?.relationElement;
            if (relationElement) {
                relationElement.paths[0] = accessPoint.id;
            }
        }
    };
    const updateAccessPointName = action((event) => {
        if (event.target.value.match(/^[0-9a-zA-Z_]*$/)) {
            accessPoint.id = event.target.value;
        }
    });
    return editingName ? (_jsx("textarea", { className: "access-point-editor__name", spellCheck: false, value: accessPoint.id, onChange: updateAccessPointName, placeholder: 'Access Point Name', onBlur: handleNameBlur, style: {
            borderColor: accessPoint.id === newNamePlaceholder
                ? 'var(--color-red-300)'
                : 'transparent',
        } })) : (_jsx("div", { className: "access-point-editor__name__label", onClick: handleNameEdit, title: "Click to edit access point name", style: { flex: '1 1 auto' }, children: accessPoint.id }));
});
const AccessPointClassification = observer((props) => {
    const { accessPoint, groupState } = props;
    const applicationStore = useEditorStore().applicationStore;
    const CHOOSE_CLASSIFICATION = 'Classification';
    const updateAccessPointClassificationTextbox = action((event) => {
        accessPoint.classification = event.target.value;
    });
    const conditionalClassifications = () => {
        if (groupState.containsPublicStereotype) {
            return (applicationStore.config.options.dataProductConfig
                ?.publicClassifications ?? []);
        }
        else {
            return (applicationStore.config.options.dataProductConfig?.classifications ??
                []);
        }
    };
    const classificationOptions = [CHOOSE_CLASSIFICATION]
        .concat(conditionalClassifications())
        .map((classfication) => ({
        label: classfication,
        value: classfication,
    }));
    const updateAccessPointClassificationFromDropdown = action((val) => {
        accessPoint_setClassification(accessPoint, val?.value === CHOOSE_CLASSIFICATION ? undefined : val?.value);
    });
    const currentClassification = accessPoint.classification !== undefined
        ? {
            label: accessPoint.classification,
            value: accessPoint.classification,
        }
        : {
            label: CHOOSE_CLASSIFICATION,
            value: CHOOSE_CLASSIFICATION,
        };
    const classificationDocumentationLink = () => {
        const docLink = applicationStore.config.options.dataProductConfig?.classificationDoc;
        if (docLink) {
            applicationStore.navigationService.navigator.visitAddress(docLink);
        }
    };
    return (_jsxs("div", { className: "access-point-editor__classification", children: [classificationOptions.length > 1 ? (_jsx("div", { style: {
                    borderWidth: 'thin',
                    borderColor: currentClassification.label === CHOOSE_CLASSIFICATION
                        ? 'var(--color-red-300)'
                        : 'transparent',
                }, children: _jsx(CustomSelectorInput, { className: "explorer__new-element-modal__driver__dropdown", options: classificationOptions, onChange: updateAccessPointClassificationFromDropdown, value: currentClassification, darkMode: !applicationStore.layoutService
                        .TEMPORARY__isLightColorThemeEnabled }) })) : (_jsx("textarea", { className: "panel__content__form__section__input", spellCheck: false, value: accessPoint.classification ?? '', onChange: updateAccessPointClassificationTextbox, placeholder: "Add classification", style: {
                    overflow: 'hidden',
                    width: '125px',
                    resize: 'none',
                    padding: '0.25rem',
                } })), _jsx(Tooltip, { title: "Learn more about data classification scheme here.", arrow: true, placement: 'top', children: _jsx("button", { onClick: classificationDocumentationLink, children: _jsx(InfoCircleIcon, {}) }) })] }));
});
const AccessPointGenerationViewer = observer((props) => {
    const { accessPointState, generationOutput } = props;
    const editorStore = accessPointState.state.state.editorStore;
    const closeDebug = () => {
        accessPointState.setArtifactContent(undefined);
    };
    return (_jsx(Dialog, { open: accessPointState.artifactGenerationContent !== undefined, onClose: closeDebug, classes: {
            root: 'editor-modal__root-container',
            container: 'editor-modal__container',
            paper: 'editor-modal__content',
        }, children: _jsxs(Modal, { className: "editor-modal", darkMode: !editorStore.applicationStore.layoutService
                .TEMPORARY__isLightColorThemeEnabled, children: [_jsx(ModalHeader, { title: `${accessPointState.accessPoint.id} Plan Generation` }), _jsx(ModalBody, { children: _jsx("div", { className: "panel__content execution-plan-viewer__panel__content", children: _jsx(CodeEditor, { inputValue: generationOutput, isReadOnly: true, language: CODE_EDITOR_LANGUAGE.JSON, hidePadding: true, hideMinimap: true }) }) }), _jsx(ModalFooter, { children: _jsx(ModalFooterButton, { title: "Close plan generation modal", onClick: closeDebug, text: "Close", type: "secondary" }) })] }) }));
});
const SampleValuesEditorModal = observer((props) => {
    const { accessPointState, isReadOnly } = props;
    const editorStore = accessPointState.state.state.editorStore;
    const dataElementPath = accessPointState.relationElementExistsinDataElementReference();
    const closeModal = () => {
        accessPointState.setShowSampleValuesModal(false);
    };
    const handleDeleteSampleValues = () => {
        editorStore.applicationStore.alertService.setActionAlertInfo({
            message: `Are you sure you want to delete sample values for Access Point ${accessPointState.accessPoint.id}?`,
            type: ActionAlertType.CAUTION,
            actions: [
                {
                    label: 'Confirm',
                    type: ActionAlertActionType.PROCEED_WITH_CAUTION,
                    handler: () => {
                        accessPointState.deleteRelationElement();
                        closeModal();
                    },
                },
                {
                    label: 'Cancel',
                    type: ActionAlertActionType.PROCEED,
                    default: true,
                },
            ],
        });
    };
    const handleNavigateToDataElement = () => {
        if (dataElementPath) {
            const dataElement = editorStore.graphManagerState.graph.getNullableElement(dataElementPath);
            if (dataElement) {
                editorStore.graphEditorMode.openElement(dataElement);
                closeModal();
            }
        }
    };
    return (_jsx(Dialog, { open: accessPointState.showSampleValuesModal, onClose: closeModal, classes: {
            root: 'editor-modal__root-container',
            container: 'editor-modal__container',
            paper: 'editor-modal__content',
        }, children: _jsxs(Modal, { className: "editor-modal", darkMode: !editorStore.applicationStore.layoutService
                .TEMPORARY__isLightColorThemeEnabled, children: [_jsx(ModalHeader, { title: `${accessPointState.accessPoint.title ?? accessPointState.accessPoint.id} Sample Values` }), _jsx(ModalBody, { children: _jsx("div", { style: {
                            padding: 0,
                            height: '100%',
                            flex: 1,
                            overflowY: 'auto',
                            overflowX: 'hidden',
                        }, children: dataElementPath !== undefined ? (_jsxs("div", { style: {
                                padding: '1.5rem',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                gap: '1rem',
                            }, children: [_jsx("span", { style: {
                                        color: 'var(--color-light-grey-200)',
                                        whiteSpace: 'nowrap',
                                        fontSize: '1.3rem',
                                        fontWeight: 600,
                                    }, children: "Sample Values already in Data Element" }), _jsxs("div", { style: {
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '0.5rem',
                                        padding: '0.5rem 1rem',
                                        background: 'var(--color-dark-grey-100)',
                                        border: '1px solid var(--color-dark-grey-300)',
                                        borderRadius: '0.2rem',
                                    }, children: [_jsx("span", { style: {
                                                fontSize: '1.3rem',
                                                fontWeight: 600,
                                                color: 'var(--color-light-grey-200)',
                                            }, children: dataElementPath }), _jsx("button", { className: "btn--sm btn--dark", onClick: handleNavigateToDataElement, tabIndex: -1, title: "Navigate to data element", style: {
                                                padding: '0.3rem 0.5rem',
                                                display: 'flex',
                                                alignItems: 'center',
                                            }, children: _jsx(LongArrowRightIcon, {}) })] })] })) : (_jsxs(_Fragment, { children: [_jsx("div", { style: {
                                        color: 'var(--color-orange-200)',
                                        fontWeight: 'bold',
                                        fontSize: '14px',
                                        padding: '0.5rem',
                                        marginBottom: '1rem',
                                        textAlign: 'center',
                                        backgroundColor: 'var(--color-orange-50)',
                                        border: '2px solid var(--color-orange-200)',
                                        borderRadius: '4px',
                                    }, children: "DO NOT ADD SENSITIVE DATA" }), accessPointState.relationElementState && (_jsx(Tooltip, { title: accessPointState.getRelationElementMismatchMessage() ??
                                        '', arrow: true, placement: "top", disableHoverListener: !accessPointState.hasRelationElementMismatch, children: _jsx("div", { style: {
                                            border: accessPointState.hasRelationElementMismatch
                                                ? '2px solid var(--color-red-300)'
                                                : 'none',
                                            borderRadius: '4px',
                                            padding: accessPointState.hasRelationElementMismatch
                                                ? '0.5rem'
                                                : '0',
                                        }, children: _jsx(RelationElementEditor, { relationElementState: accessPointState.relationElementState, isReadOnly: isReadOnly }) }) }))] })) }) }), _jsxs(ModalFooter, { children: [dataElementPath === undefined && (_jsx(ModalFooterButton, { title: "Delete sample values", onClick: handleDeleteSampleValues, text: "Delete", type: "secondary", disabled: isReadOnly })), _jsx(ModalFooterButton, { title: "Close sample values editor", onClick: closeModal, text: "Close", type: "secondary" })] })] }) }));
});
export const LakehouseDataProductAccessPointEditor = observer((props) => {
    const { accessPointState } = props;
    const editorStore = useEditorStore();
    const accessPoint = accessPointState.accessPoint;
    const groupState = accessPointState.state;
    const lambdaEditorState = accessPointState.lambdaState;
    const propertyHasParserError = groupState.accessPointStates
        .filter(filterByType(LakehouseAccessPointState))
        .find((pm) => pm.lambdaState.parserError);
    const [editingDescription, setEditingDescription] = useState(false);
    const [isHoveringDesc, setIsHoveringDesc] = useState(false);
    const [editingTitle, setEditingTitle] = useState(false);
    const [isHoveringTitle, setIsHoveringTitle] = useState(false);
    const ref = useRef(null);
    const handleEditorBlur = useCallback(() => {
        flowResult(lambdaEditorState.updateLambdaRelationColumns()).catch(editorStore.applicationStore.alertUnhandledError);
    }, [lambdaEditorState, editorStore.applicationStore]);
    const handleDescriptionEdit = () => setEditingDescription(true);
    const handleDescriptionBlur = () => {
        setEditingDescription(false);
        setIsHoveringDesc(false);
    };
    const handleMouseOverDesc = () => {
        setIsHoveringDesc(true);
    };
    const handleMouseOutDesc = () => {
        setIsHoveringDesc(false);
    };
    const handleTitleEdit = () => setEditingTitle(true);
    const handleTitleBlur = () => {
        setEditingTitle(false);
        setIsHoveringTitle(false);
    };
    const handleMouseOverTitle = () => {
        setIsHoveringTitle(true);
    };
    const handleMouseOutTitle = () => {
        setIsHoveringTitle(false);
    };
    const updateAccessPointTargetEnvironment = action((targetEnvironment) => {
        accessPoint.targetEnvironment = targetEnvironment;
    });
    const debugPlanGeneration = editorStore.applicationStore.guardUnhandledError(() => flowResult(accessPointState.generateArtifact()));
    const handleRemoveAccessPoint = () => {
        editorStore.applicationStore.alertService.setActionAlertInfo({
            message: `Are you sure you want to delete Access Point ${accessPoint.id}?`,
            type: ActionAlertType.CAUTION,
            actions: [
                {
                    label: 'Confirm',
                    type: ActionAlertActionType.PROCEED_WITH_CAUTION,
                    handler: () => {
                        groupState.deleteAccessPoint(accessPointState);
                    },
                },
                {
                    label: 'Cancel',
                    type: ActionAlertActionType.PROCEED,
                    default: true,
                },
            ],
        });
    };
    //Drag and drop - reorder access points/move between groups
    const handleHover = useCallback((item) => {
        const draggingProperty = item.accessPointState;
        const hoveredProperty = accessPointState;
        groupState.swapAccessPoints(draggingProperty, hoveredProperty);
    }, [accessPointState, groupState]);
    const [{ isBeingDraggedAP }, dropConnector] = useDrop(() => ({
        accept: [AP_DND_TYPE],
        hover: (item) => handleHover(item),
        collect: (monitor) => ({
            isBeingDraggedAP: monitor.getItem()
                ?.accessPointState,
        }),
    }), [handleHover]);
    const isBeingDragged = accessPoint === isBeingDraggedAP?.accessPoint;
    const [, dragConnector, dragPreviewConnector] = useDrag(() => ({
        type: AP_DND_TYPE,
        item: () => ({
            accessPointState: accessPointState,
        }),
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
        }),
    }), [accessPointState]);
    dragConnector(ref);
    dropConnector(ref);
    useDragPreviewLayer(dragPreviewConnector);
    const generateLineage = editorStore.applicationStore.guardUnhandledError(() => flowResult(accessPointState.generateLineage()));
    return (_jsx(PanelDnDEntry, { ref: ref, placeholder: _jsx("div", { className: "dnd__placeholder--light" }), showPlaceholder: isBeingDragged, children: _jsxs("div", { className: clsx('access-point-editor', {
                backdrop__element: propertyHasParserError,
            }), children: [_jsx(PanelEntryDragHandle, { dragSourceConnector: ref, isDragging: isBeingDragged, title: 'Drag this Access Point to another group', className: "access-point-editor__dnd-handle" }), _jsxs("div", { style: { flex: 1 }, children: [_jsxs("div", { className: "access-point-editor__metadata", children: [_jsx(AccessPointTitle, { accessPointState: accessPointState }), _jsxs("div", { className: "access-point-editor__info", children: [_jsxs("div", { className: "access-point-editor__reproducible", children: [_jsx(Checkbox, { disabled: groupState.state.isReadOnly, checked: accessPoint.reproducible ?? false, onChange: () => accessPoint_setReproducible(accessPoint, !accessPoint.reproducible), size: "small", style: { padding: 0, margin: 0 } }), _jsx(Tooltip, { title: _jsx("div", { style: {
                                                            maxWidth: '400px',
                                                            whiteSpace: 'normal',
                                                            wordWrap: 'break-word',
                                                        }, children: "Marking as \"reproducible\" means consumers can consistently retrieve the exact historical data as it existed at any specific Lakehouse batch." }), arrow: true, placement: 'top', children: _jsx("div", { children: "Reproducible" }) })] }), accessPointState.relationElementExistsinDataElementReference() !==
                                            undefined ? (_jsxs("button", { className: "access-point-editor__sample-values-btn", onClick: () => accessPointState.setShowSampleValuesModal(true), disabled: props.isReadOnly, title: "Edit sample values", style: {
                                                border: '1px solid var(--color-blue-200)',
                                                borderRadius: '4px',
                                                padding: '0.5rem 0.75rem',
                                                background: 'var(--color-blue-200)',
                                                cursor: props.isReadOnly ? 'not-allowed' : 'pointer',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '0.5rem',
                                                color: 'white',
                                                fontSize: '1.2rem',
                                                whiteSpace: 'nowrap',
                                            }, children: [_jsx(PencilEditIcon, {}), _jsx("span", { children: "Sample Values" })] })) : accessPointState.relationElementState !== undefined ? (_jsxs("button", { className: "access-point-editor__sample-values-btn", onClick: () => accessPointState.setShowSampleValuesModal(true), disabled: props.isReadOnly, title: "Edit sample values", style: {
                                                border: accessPointState.hasRelationElementMismatch
                                                    ? '2px solid var(--color-red-300)'
                                                    : '1px solid var(--color-blue-200)',
                                                borderRadius: '4px',
                                                padding: '0.5rem 0.75rem',
                                                background: 'var(--color-blue-200)',
                                                cursor: props.isReadOnly ? 'not-allowed' : 'pointer',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '0.5rem',
                                                color: 'white',
                                                fontSize: '1.2rem',
                                                whiteSpace: 'nowrap',
                                            }, children: [_jsx(PencilEditIcon, {}), _jsx("span", { children: "Sample Values" })] })) : (_jsxs("button", { className: "access-point-editor__sample-values-btn", onClick: () => {
                                                accessPointState.createAndaddRelationElement();
                                            }, disabled: props.isReadOnly, title: "Add sample values", style: {
                                                border: '1px solid var(--color-blue-200)',
                                                borderRadius: '4px',
                                                padding: '0.5rem 0.75rem',
                                                background: 'var(--color-blue-200)',
                                                cursor: props.isReadOnly ? 'not-allowed' : 'pointer',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '0.5rem',
                                                color: 'white',
                                                fontSize: '1.2rem',
                                                whiteSpace: 'nowrap',
                                            }, children: [_jsx(PlusIcon, {}), _jsx("span", { children: "Sample Values" })] })), editorStore.applicationStore.config.options
                                            .dataProductConfig && (_jsx(AccessPointClassification, { accessPoint: accessPoint, groupState: groupState })), _jsxs("div", { className: clsx('access-point-editor__type'), title: 'Change target environment', children: [_jsx("div", { className: "access-point-editor__type__label", children: accessPoint.targetEnvironment }), _jsx(ControlledDropdownMenu, { className: "access-point-editor__dropdown", content: _jsx(MenuContent, { children: Object.values(LakehouseTargetEnv).map((environment) => (_jsx(MenuContentItem, { className: "btn__dropdown-combo__option", onClick: () => updateAccessPointTargetEnvironment(environment), children: environment }, environment))) }), menuProps: {
                                                        anchorOrigin: {
                                                            vertical: 'bottom',
                                                            horizontal: 'right',
                                                        },
                                                        transformOrigin: {
                                                            vertical: 'top',
                                                            horizontal: 'right',
                                                        },
                                                    }, children: _jsx(CaretDownIcon, {}) })] }), _jsx(ControlledDropdownMenu, { className: "access-point-editor__dropdown", content: _jsxs(MenuContent, { children: [_jsx(MenuContentItem, { className: "btn__dropdown-combo__option", onClick: debugPlanGeneration, children: _jsxs("div", { style: {
                                                                display: 'flex',
                                                                gap: '0.5rem',
                                                                alignItems: 'center',
                                                            }, children: [_jsx(BugIcon, {}), " ", _jsx("span", { children: "AP Plan Generation" })] }) }), _jsx(MenuContentItem, { className: "btn__dropdown-combo__option", onClick: generateLineage, children: _jsxs("div", { style: {
                                                                display: 'flex',
                                                                gap: '0.5rem',
                                                                alignItems: 'center',
                                                            }, children: [_jsx("span", { style: {
                                                                        display: 'flex',
                                                                        alignItems: 'center',
                                                                        transform: 'rotate(90deg)',
                                                                    }, children: _jsx(GitBranchIcon, {}) }), _jsx("span", { children: "Lineage Viewer" })] }) })] }), menuProps: {
                                                anchorOrigin: { vertical: 'bottom', horizontal: 'right' },
                                                transformOrigin: { vertical: 'top', horizontal: 'right' },
                                            }, children: _jsx("div", { className: "access-point-editor__generic-entry__remove-btn__debug", tabIndex: -1, title: "Access Point Tools", style: {
                                                    background: 'var(--color-blue-200)',
                                                    borderRadius: '4px',
                                                    marginRight: '1.5rem',
                                                    padding: '0.25rem 0.5rem',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    color: 'white',
                                                }, children: _jsx(ListIcon, {}) }) })] })] }), editingTitle ? (_jsx("textarea", { className: "access-point-editor__name", spellCheck: false, value: accessPoint.title, onChange: (event) => accessPoint_setTitle(accessPoint, event.target.value), placeholder: 'Access Point Title', onBlur: handleTitleBlur, style: {
                                borderColor: 'transparent',
                                margin: '0.5rem',
                            } })) : (_jsxs("div", { onClick: handleTitleEdit, title: "Click to edit access point title", className: "access-point-editor__description-container", children: [accessPoint.title ? (_jsx(HoverTextArea, { text: accessPoint.title, handleMouseOver: handleMouseOverTitle, handleMouseOut: handleMouseOutTitle, className: "access-point-editor__title" })) : (_jsxs("div", { className: "access-point-editor__group-container__description--warning", onMouseOver: handleMouseOverTitle, onMouseOut: handleMouseOutTitle, style: { fontSize: '15px' }, children: [_jsx(ErrorWarnIcon, {}), "Provide a title for this Access Point"] })), isHoveringTitle && hoverIcon()] })), editingDescription ? (_jsx("textarea", { className: "panel__content__form__section__input", spellCheck: false, value: accessPoint.description ?? '', onChange: (event) => accessPoint_setDescription(accessPoint, event.target.value), placeholder: "Access Point description", onBlur: handleDescriptionBlur, style: {
                                resize: 'vertical',
                                padding: '0.25rem',
                                marginLeft: '0.5rem',
                                marginTop: '0.5rem',
                                height: 'auto',
                            } })) : (_jsxs("div", { onClick: handleDescriptionEdit, title: "Click to edit access point description", className: "access-point-editor__description-container", children: [accessPoint.description ? (_jsx(HoverTextArea, { text: accessPoint.description, handleMouseOver: handleMouseOverDesc, handleMouseOut: handleMouseOutDesc })) : (_jsxs("div", { className: "access-point-editor__group-container__description--warning", onMouseOver: handleMouseOverDesc, onMouseOut: handleMouseOutDesc, children: [_jsx(ErrorWarnIcon, {}), AP_EMPTY_DESC_WARNING] })), isHoveringDesc && hoverIcon()] })), _jsx("div", { className: "access-point-editor__content", children: _jsx("div", { className: "access-point-editor__generic-entry", children: _jsx("div", { className: "access-point-editor__entry__container", children: _jsx("div", { className: "access-point-editor__entry", children: _jsx(InlineLambdaEditor, { className: 'access-point-editor__lambda-editor', disabled: lambdaEditorState.val.state.state
                                                .isConvertingTransformLambdaObjects, lambdaEditorState: lambdaEditorState, forceBackdrop: Boolean(lambdaEditorState.parserError), onEditorBlur: handleEditorBlur }) }) }) }) }), _jsx(LineageViewer, { lineageState: accessPointState.lineageState })] }), _jsx("button", { className: "access-point-editor__generic-entry__remove-btn", onClick: () => {
                        handleRemoveAccessPoint();
                    }, tabIndex: -1, title: "Remove", children: _jsx(TimesIcon, {}) }), accessPointState.artifactGenerationContent && (_jsx(AccessPointGenerationViewer, { accessPointState: accessPointState, generationOutput: accessPointState.artifactGenerationContent })), accessPointState.showSampleValuesModal && (_jsx(SampleValuesEditorModal, { accessPointState: accessPointState, isReadOnly: props.isReadOnly }))] }) }));
});
const DataProductDeploymentResponseModal = observer((props) => {
    const { state } = props;
    const applicationStore = state.editorStore.applicationStore;
    const closeModal = () => state.setDeployResponse(undefined);
    return (_jsx(Dialog, { open: Boolean(state.deployResponse), classes: {
            root: 'editor-modal__root-container',
            container: 'editor-modal__container',
            paper: 'editor-modal__content',
        }, onClose: closeModal, children: _jsxs(Modal, { darkMode: !applicationStore.layoutService.TEMPORARY__isLightColorThemeEnabled, className: "editor-modal", children: [_jsx(ModalHeader, { children: _jsx(ModalTitle, { title: "Data Product Deployment Response" }) }), _jsx(ModalBody, { children: _jsx(PanelContent, { children: _jsx(CodeEditor, { inputValue: JSON.stringify(state.deployResponse?.content ?? {}, null, 2), isReadOnly: true, language: CODE_EDITOR_LANGUAGE.JSON }) }) }), _jsx(ModalFooter, { children: _jsx(ModalFooterButton, { onClick: closeModal, text: "Close", type: "secondary" }) })] }) }));
});
const AccessPointGroupPublicToggle = observer((props) => {
    const { groupState } = props;
    const handleSwitchChange = (event) => {
        const isChecked = event.target.checked;
        if (isChecked && groupState.publicStereotype) {
            annotatedElement_addStereotype(groupState.value, StereotypeExplicitReference.create(groupState.publicStereotype));
        }
        else if (groupState.containsPublicStereotype) {
            annotatedElement_deleteStereotype(groupState.value, groupState.containsPublicStereotype);
        }
    };
    return (_jsxs("div", { className: "access-point-editor__toggle", children: [_jsx(Switch, { checked: Boolean(groupState.containsPublicStereotype), onChange: handleSwitchChange, sx: {
                    '& .MuiSwitch-track': {
                        backgroundColor: groupState.containsPublicStereotype
                            ? 'default'
                            : 'var(--color-light-grey-400)',
                    },
                } }), _jsx(BuildingIcon, {}), "Enterprise Data. Anyone at the firm can access this without approvals."] }));
});
export const CompatibleDiagramsEditor = observer((props) => {
    const { groupState } = props;
    const group = groupState.value;
    const handleDiagramTitleChange = (diagram, value) => {
        dataProductDiagram_setTitle(diagram, value ?? '');
    };
    const handleDiagramDescriptionChange = (diagram, value) => {
        dataProductDiagram_setDescription(diagram, value);
    };
    const handleAddDiagram = (option) => {
        groupState.addDiagram(option);
    };
    const handleRemoveDiagram = (diagram) => {
        groupState.handleRemoveDiagram(diagram);
    };
    // ListEditor component renderers
    const DiagramComponent = observer((diagramComponentProps) => {
        const { item } = diagramComponentProps;
        return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "panel__content__form__section__list__item__content", children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Diagram" }), _jsx("div", { className: "panel__content__form__section__list__item__content__title", children: item.title })] }), _jsxs("div", { className: "panel__content__form__section__list__item__form", children: [_jsx(PanelFormTextField, { name: "Title", value: item.title, update: (value) => handleDiagramTitleChange(item, value), placeholder: "Enter title", className: "dataSpace-editor__general__diagrams__title" }), _jsx(PanelFormTextField, { name: "Description", value: item.description ?? '', update: (value) => handleDiagramDescriptionChange(item, value), placeholder: "Enter description", className: "dataSpace-editor__general__diagrams__description" })] })] }));
    });
    const NewDiagramComponent = observer((newDiagramProps) => {
        const { onFinishEditing } = newDiagramProps;
        return (_jsx("div", { className: "panel__content__form__section__list__new-item__input", children: _jsx(CustomSelectorInput, { options: groupState.getCompatibleDiagramOptions(), onChange: (event) => {
                    onFinishEditing();
                    handleAddDiagram(event);
                }, placeholder: "Select a diagram to add...", darkMode: !groupState.state.editorStore.applicationStore.layoutService
                    .TEMPORARY__isLightColorThemeEnabled }) }));
    });
    return (_jsx(ListEditor, { title: "Diagrams", prompt: "Add diagrams to include in this Data Product. Set a title and description for each diagram.", items: group.diagrams, keySelector: (element) => element.hashCode, ItemComponent: DiagramComponent, NewItemComponent: NewDiagramComponent, handleRemoveItem: handleRemoveDiagram, isReadOnly: groupState.state.isReadOnly, emptyMessage: "No Diagrams specified", emptyClassName: "data-product-editor__empty-diagram" }));
});
export const FeaturedElementsEditor = observer((props) => {
    const { groupState, isReadOnly } = props;
    const group = groupState.value;
    // Event handlers
    const handleAddElement = (option) => {
        if (typeof option.value === 'object') {
            groupState.addFeaturedElement(option.value);
        }
    };
    const handleRemoveElement = (element) => {
        groupState.removeFeaturedElement(element);
    };
    const handleElementExcludeChange = (element, event) => {
        groupState.excludeFeaturedElement(element, event.target.checked);
    };
    // ListEditor component renderers
    const ElementComponent = observer((elementComponentProps) => {
        const { item } = elementComponentProps;
        return (_jsxs("div", { className: "data-product-editor__element-item", children: [_jsx("div", { className: "panel__content__form__section__list__item__content__label", children: item.element.value.path }), _jsx("div", { className: "panel__content__form__section__list__item__content__actions", children: _jsxs("div", { className: "panel__content__form__section__list__item__content__actions-exclude", children: [_jsx(Checkbox, { disabled: isReadOnly, checked: item.exclude ?? false, onChange: (event) => handleElementExcludeChange(item, event), size: "small", className: "panel__content__form__section__list__item__content__actions-exclude__btn" }), _jsx("span", { className: "panel__content__form__section__list__item__content__actions__label", children: "Exclude" })] }) })] }));
    });
    const NewElementComponent = observer((newElementProps) => {
        const { onFinishEditing } = newElementProps;
        return (_jsx("div", { className: "panel__content__form__section__list__new-item__input", children: _jsx(CustomSelectorInput, { options: groupState.getFeaturedElementOptions(), onChange: (event) => {
                    onFinishEditing();
                    handleAddElement(event);
                }, placeholder: "Select an element to add...", darkMode: !groupState.state.editorStore.applicationStore.layoutService
                    .TEMPORARY__isLightColorThemeEnabled }) }));
    });
    return (_jsx(ListEditor, { title: "Featured Elements", prompt: "Add classes and associations to display under Models Documentation. Use the exclude checkbox to exclude certain elements from this Data Product entirely.", items: group.featuredElements, keySelector: (element) => element.element.value.path, ItemComponent: ElementComponent, NewItemComponent: NewElementComponent, handleRemoveItem: handleRemoveElement, isReadOnly: isReadOnly, emptyMessage: "No elements specified" }));
});
const ModelAccessPointGroupEditor = observer((props) => {
    const { groupState, isReadOnly } = props;
    const editorStore = useEditorStore();
    // mapping
    const mapping = groupState.value.mapping;
    const isMappingEmpty = validate_PureExecutionMapping(groupState.value.mapping.value);
    const mappingOptions = groupState.state.editorStore.graphManagerState.usableMappings.map(buildElementOption);
    const selectedMappingOption = {
        value: mapping.value,
        label: mapping.value.path === '' ? '(none)' : mapping.value.path,
    };
    const onMappingChange = (val) => {
        if (val.value !== mapping.value) {
            groupState.setMapping(val.value);
        }
    };
    const visitElement = (element) => {
        editorStore.graphEditorMode.openElement(element);
    };
    return (_jsxs("div", { className: "data-product-editor__model-apg-editor", children: [_jsx("div", { className: "data-product-editor__model-apg-editor__label", children: "Mapping" }), _jsxs("div", { className: "service-execution-editor__configuration__item", style: { padding: '0 1rem' }, children: [_jsx("div", { className: "btn--sm service-execution-editor__configuration__item__label", children: _jsx(PURE_MappingIcon, {}) }), _jsx(CustomSelectorInput, { className: "panel__content__form__section__dropdown service-execution-editor__configuration__item__dropdown", disabled: isReadOnly, options: mappingOptions, onChange: onMappingChange, value: selectedMappingOption, darkMode: !groupState.state.editorStore.applicationStore.layoutService
                            .TEMPORARY__isLightColorThemeEnabled, hasError: Boolean(isMappingEmpty) }), _jsx("button", { className: "btn--dark btn--sm service-execution-editor__configuration__item__btn", onClick: () => {
                            visitElement(groupState.value.mapping.value);
                        }, tabIndex: -1, title: "See mapping", disabled: Boolean(isMappingEmpty), children: _jsx(LongArrowRightIcon, {}) })] }), _jsx(CompatibleDiagramsEditor, { groupState: groupState }), _jsx(FeaturedElementsEditor, { groupState: groupState, isReadOnly: isReadOnly })] }));
});
const AccessPointGroupEditor = observer((props) => {
    const { groupState, isReadOnly } = props;
    const editorStore = useEditorStore();
    const productEditorState = groupState.state;
    const [editingDescription, setEditingDescription] = useState(false);
    const [isHoveringDescription, setIsHoveringDescription] = useState(false);
    const [editingName, setEditingName] = useState(groupState.value.id === newNamePlaceholder);
    const [isHoveringName, setIsHoveringName] = useState(false);
    const [editingTitle, setEditingTitle] = useState(false);
    const [isHoveringTitle, setIsHoveringTitle] = useState(false);
    const handleDescriptionEdit = () => setEditingDescription(true);
    const handleDescriptionBlur = () => {
        setEditingDescription(false);
        setIsHoveringDescription(false);
    };
    const handleMouseOverDescription = () => {
        setIsHoveringDescription(true);
    };
    const handleMouseOutDescription = () => {
        setIsHoveringDescription(false);
    };
    const updateGroupDescription = (val) => {
        accessPointGroup_setDescription(groupState.value, val);
    };
    const handleNameEdit = () => setEditingName(true);
    const handleNameBlur = () => {
        if (groupState.value.id !== newNamePlaceholder) {
            setEditingName(false);
            setIsHoveringName(false);
        }
    };
    const handleMouseOverName = () => {
        setIsHoveringName(true);
    };
    const handleMouseOutName = () => {
        setIsHoveringName(false);
    };
    const updateGroupName = (val) => {
        if (val.match(/^[0-9a-zA-Z_]+$/)) {
            accessPointGroup_setName(groupState.value, val);
        }
    };
    const handleTitleEdit = () => setEditingTitle(true);
    const handleTitleBlur = () => {
        setEditingTitle(false);
        setIsHoveringTitle(false);
    };
    const handleMouseOverTitle = () => {
        setIsHoveringTitle(true);
    };
    const handleMouseOutTitle = () => {
        setIsHoveringTitle(false);
    };
    const updateGroupTitle = (val) => {
        accessPointGroup_setTitle(groupState.value, val);
    };
    const handleRemoveAccessPointGroup = () => {
        editorStore.applicationStore.alertService.setActionAlertInfo({
            message: `Are you sure you want to delete Access Point Group ${groupState.value.id} and all of its Access Points?`,
            type: ActionAlertType.CAUTION,
            actions: [
                {
                    label: 'Confirm',
                    type: ActionAlertActionType.PROCEED_WITH_CAUTION,
                    handler: () => {
                        productEditorState.deleteAccessPointGroup(groupState);
                    },
                },
                {
                    label: 'Cancel',
                    type: ActionAlertActionType.PROCEED,
                    default: true,
                },
            ],
        });
    };
    const handleAddAccessPoint = () => {
        productEditorState.addAccessPoint(newNamePlaceholder, undefined, productEditorState.selectedGroupState ?? groupState);
    };
    return (_jsxs("div", { className: "access-point-editor__group-container", "data-testid": LEGEND_STUDIO_TEST_ID.ACCESS_POINT_GROUP_EDITOR, children: [_jsx(PanelLoadingIndicator, { isLoading: groupState.isRunningProcess }), _jsxs("div", { className: "access-point-editor__group-container__name-editor", children: [editingName ? (_jsx("textarea", { className: "panel__content__form__section__input", spellCheck: false, value: groupState.value.id, onChange: (event) => updateGroupName(event.target.value), placeholder: "Access Point Group Name", onBlur: handleNameBlur, style: {
                            overflow: 'hidden',
                            resize: 'none',
                            padding: '0.25rem',
                            borderColor: groupState.value.id === newNamePlaceholder
                                ? 'var(--color-red-300)'
                                : 'transparent',
                            borderWidth: 'thin',
                        } })) : (_jsxs("div", { onClick: handleNameEdit, title: "Click to edit group name", className: "access-point-editor__group-container__name", children: [_jsx(HoverTextArea, { text: groupState.value.id, handleMouseOver: handleMouseOverName, handleMouseOut: handleMouseOutName, className: "access-point-editor__group-container__name" }), isHoveringName && hoverIcon()] })), !groupState.state.modelledDataProduct && (_jsx("button", { className: "access-point-editor__generic-entry__remove-btn--group", onClick: () => {
                            handleRemoveAccessPointGroup();
                        }, tabIndex: -1, title: "Remove Access Point Group", children: _jsx(TimesIcon, {}) }))] }), _jsx("div", { className: "access-point-editor__group-container__name-editor", children: editingTitle ? (_jsx("textarea", { className: "panel__content__form__section__input", spellCheck: false, value: groupState.value.title, onChange: (event) => updateGroupTitle(event.target.value), placeholder: "Access Point Group Title", onBlur: handleTitleBlur, style: {
                        overflow: 'hidden',
                        resize: 'none',
                        padding: '0.25rem',
                        margin: '0.5rem 0.5rem 0.5rem 0rem',
                    } })) : (_jsxs("div", { onClick: handleTitleEdit, title: "Click to edit group title", className: "access-point-editor__group-container__description", children: [groupState.value.title ? (_jsx(HoverTextArea, { text: groupState.value.title, handleMouseOver: handleMouseOverTitle, handleMouseOut: handleMouseOutTitle, className: "access-point-editor__group-container__title" })) : (_jsxs("div", { className: "access-point-editor__group-container__description--warning", onMouseOver: handleMouseOverTitle, onMouseOut: handleMouseOutTitle, style: { fontSize: '15px' }, children: [_jsx(ErrorWarnIcon, {}), "Provide a title for this Access Point Group"] })), isHoveringTitle && hoverIcon()] })) }), _jsx("div", { className: "access-point-editor__group-container__description-editor", children: editingDescription ? (_jsx("textarea", { className: "panel__content__form__section__input", spellCheck: false, value: groupState.value.description ?? '', onChange: (event) => updateGroupDescription(event.target.value), placeholder: "Provide a description for this Access Point Group", onBlur: handleDescriptionBlur, style: {
                        overflow: 'hidden',
                        padding: '0.25rem',
                        height: 'auto',
                    } })) : (_jsxs("div", { onClick: handleDescriptionEdit, title: "Click to edit group description", className: "access-point-editor__description-container", children: [groupState.value.description ? (_jsx(HoverTextArea, { text: groupState.value.description, handleMouseOver: handleMouseOverDescription, handleMouseOut: handleMouseOutDescription, className: "access-point-editor__group-container__description" })) : (_jsxs("div", { className: "access-point-editor__group-container__description--warning", onMouseOver: handleMouseOverDescription, onMouseOut: handleMouseOutDescription, children: [_jsx(ErrorWarnIcon, {}), "Users request access at the access point group level. Click here to add a meaningful description to guide users."] })), isHoveringDescription && hoverIcon()] })) }), editorStore.applicationStore.config.options.dataProductConfig && (_jsx(AccessPointGroupPublicToggle, { groupState: groupState })), groupState instanceof ModelAccessPointGroupState && (_jsx(ModelAccessPointGroupEditor, { groupState: groupState, isReadOnly: isReadOnly })), _jsxs(PanelHeader, { className: "panel__header--access-point", children: [_jsx("div", { className: "panel__header__title", children: "Access Points" }), _jsx(PanelHeaderActions, { children: _jsx(PanelHeaderActionItem, { className: "panel__header__action", onClick: handleAddAccessPoint, title: "Create new access point", children: _jsx(PlusIcon, {}) }) })] }), groupState.accessPointStates.length === 0 && (_jsxs("div", { className: "access-point-editor__group-container__description--warning", style: { color: 'var(--color-red-300)' }, children: [_jsx(WarningIcon, {}), "This group needs at least one access point defined."] })), _jsx("div", { style: { gap: '1rem', display: 'flex', flexDirection: 'column' }, children: groupState.accessPointStates
                    .filter(filterByType(LakehouseAccessPointState))
                    .map((apState) => (_jsx(LakehouseDataProductAccessPointEditor, { isReadOnly: isReadOnly, accessPointState: apState }, apState.uuid))) })] }));
});
const GroupTabRenderer = observer((props) => {
    const { group, dataProductEditorState } = props;
    const changeGroup = (newGroup) => {
        dataProductEditorState.setSelectedGroupState(newGroup);
    };
    const selectedGroupState = dataProductEditorState.selectedGroupState;
    const ref = useRef(null);
    //Drag and Drop - reorder groups and accept access points from other groups
    const handleHover = useCallback((item) => {
        const draggingProperty = item.groupState;
        const hoveredProperty = group;
        dataProductEditorState.swapAccessPointGroups(draggingProperty, hoveredProperty);
    }, [group, dataProductEditorState]);
    const [{ isOver }, dropConnector] = useDrop(() => ({
        accept: [AP_GROUP_DND_TYPE, AP_DND_TYPE],
        hover: (item, monitor) => {
            const itemType = monitor.getItemType();
            if (itemType === AP_GROUP_DND_TYPE) {
                const groupItem = item;
                handleHover(groupItem);
            }
        },
        drop: (item, monitor) => {
            const itemType = monitor.getItemType();
            if (itemType === AP_DND_TYPE) {
                const accessPointItem = item;
                group.addAccessPoint(accessPointItem.accessPointState);
                accessPointItem.accessPointState.state.deleteAccessPoint(accessPointItem.accessPointState);
                accessPointItem.accessPointState.changeGroupState(group);
            }
        },
        collect: (monitor) => ({
            isBeingDraggedAPG: monitor.getItemType() === AP_GROUP_DND_TYPE
                ? monitor.getItem()?.groupState
                : undefined,
            isBeingDraggedAP: monitor.getItemType() === AP_DND_TYPE
                ? monitor.getItem()
                    ?.accessPointState
                : undefined,
            isOver: monitor.isOver(),
        }),
    }), [handleHover]);
    const [, dragConnector, dragPreviewConnector] = useDrag(() => ({
        type: AP_GROUP_DND_TYPE,
        item: () => ({
            groupState: group,
        }),
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
        }),
    }), [group]);
    dragConnector(ref);
    dropConnector(ref);
    dragPreviewConnector(ref);
    return (_jsxs("div", { ref: ref, onClick: () => changeGroup(group), className: clsx('service-editor__tab', {
            'service-editor__tab--active': group === selectedGroupState,
        }), style: {
            backgroundColor: isOver
                ? 'var(--color-dark-grey-100)'
                : 'var(--color-dark-grey-50)',
        }, role: "tab", children: [group.value.id, "\u00A0", group.hasErrors() && (_jsx(ErrorWarnIcon, { title: "Resolve Access Point Group error(s)", style: { color: 'var(--color-red-300)' } }))] }, group.uuid));
});
const AccessPointGroupTab = observer((props) => {
    const { dataProductEditorState, isReadOnly } = props;
    const groupStates = dataProductEditorState.accessPointGroupStates;
    const selectedGroupState = dataProductEditorState.selectedGroupState;
    const handleAddAccessPointGroup = () => {
        const newGroup = dataProductEditorState.createGroupAndAdd(newNamePlaceholder);
        dataProductEditorState.setSelectedGroupState(newGroup);
    };
    const AccessPointDragPreviewLayer = () => (_jsx(DragPreviewLayer, { labelGetter: (item) => {
            return item.accessPointState.accessPoint.id;
        }, types: [AP_DND_TYPE] }));
    const disableAddGroup = Boolean(dataProductEditorState.accessPointGroupStates.find((group) => group.value.id === newNamePlaceholder));
    return (_jsxs("div", { className: "panel", style: { overflow: 'visible' }, children: [_jsx(AccessPointDragPreviewLayer, {}), _jsx("div", { className: "panel__content__form__section__header__label", style: { paddingLeft: '1rem' }, children: "Access Point Groups" }), _jsx(PanelHeader, { children: _jsxs("div", { className: "uml-element-editor__tabs", children: [groupStates.map((group) => {
                            return (_jsx(GroupTabRenderer, { group: group, dataProductEditorState: dataProductEditorState }, group.uuid));
                        }), !dataProductEditorState.modelledDataProduct && (_jsx(PanelHeaderActionItem, { className: "panel__header__action", onClick: handleAddAccessPointGroup, disabled: isReadOnly || disableAddGroup, title: disableAddGroup
                                ? 'Provide all group names'
                                : 'Create new access point group', children: _jsx(PlusIcon, {}) }))] }) }), _jsx(PanelContent, { children: selectedGroupState && (_jsx(AccessPointGroupEditor, { groupState: selectedGroupState, isReadOnly: isReadOnly }, selectedGroupState.uuid)) }), dataProductEditorState.deployResponse && (_jsx(DataProductDeploymentResponseModal, { state: dataProductEditorState }))] }));
});
const DataProductSidebar = observer((props) => {
    const { dataProductEditorState } = props;
    const sidebarTabs = [
        {
            label: DATA_PRODUCT_TAB.HOME,
            icon: _jsx(HomeIcon, {}),
        },
        {
            label: DATA_PRODUCT_TAB.APG,
            title: 'Access Point Groups',
            icon: _jsx(GroupWorkIcon, {}),
        },
        {
            label: DATA_PRODUCT_TAB.OPERATIONAL,
            title: 'Operational Metadata',
            icon: _jsx(GearSuggestIcon, {}),
        },
        {
            label: DATA_PRODUCT_TAB.SUPPORT,
            icon: _jsx(QuestionCircleIcon, {}),
        },
    ];
    return (_jsx("div", { className: "data-space__viewer__activity-bar", style: { position: 'static', maxHeight: '100%' }, children: _jsx("div", { className: "data-space__viewer__activity-bar__items", children: sidebarTabs.map((activity) => (_jsxs("button", { className: clsx('data-space__viewer__activity-bar__item', {
                    'data-space__viewer__activity-bar__item--active': dataProductEditorState.selectedTab === activity.label,
                }), onClick: () => dataProductEditorState.setSelectedTab(activity.label), tabIndex: -1, title: activity.title ?? activity.label, style: {
                    flexDirection: 'column',
                    fontSize: '10px',
                    margin: '0.5rem 0rem',
                }, children: [activity.icon, activity.label] }, activity.label))) }) }));
});
const IconPreviewComponent = observer((props) => {
    const { dataProduct } = props;
    if (dataProduct.icon instanceof DataProductLibraryIcon) {
        const iconId = dataProduct.icon.iconId;
        const IconComponent = IconSelectorIcons[iconId];
        return (_jsx("div", { className: "data-product-editor__icon-preview", children: IconComponent ? _jsx(IconComponent, {}) : 'No icon selected' }));
    }
    else if (dataProduct.icon instanceof DataProductEmbeddedImageIcon) {
        return (_jsx("img", { src: dataProduct.icon.imageUrl, alt: "Data Product Image", className: "data-product-editor__icon-preview__image" }));
    }
    return (_jsx("div", { className: "data-product-editor__icon-preview", children: _jsx("div", { className: "data-product-editor__icon-preview__no-icon", children: "No icon selected" }) }));
});
const IconSelectorComponent = observer((props) => {
    const { dataProduct, isReadOnly } = props;
    const handleChange = (iconId) => {
        if (iconId === undefined) {
            dataProduct_setIcon(dataProduct, undefined);
        }
        else {
            const _dataProductLibraryIcon = new DataProductLibraryIcon(V1_DataProductIconLibraryId.REACT_ICONS, iconId);
            dataProduct_setIcon(dataProduct, _dataProductLibraryIcon);
        }
    };
    return (_jsx(IconSelectorGrid, { iconId: dataProduct.icon instanceof DataProductLibraryIcon
            ? dataProduct.icon.iconId
            : undefined, onChange: handleChange, isReadOnly: isReadOnly, disableHighlightNoneOption: dataProduct.icon instanceof DataProductEmbeddedImageIcon }));
});
const ImageSelectorComponent = observer((props) => {
    const { dataProduct, isReadOnly } = props;
    const editorStore = useEditorStore();
    const imageInputRef = useRef(null);
    const imageConfig = editorStore.applicationStore.config.options.dataProductConfig
        ?.imageConfig;
    const handleFileChange = async (event) => {
        const file = event.target.files?.[0];
        if (file) {
            try {
                // Check file size first
                const fileSizeKB = file.size / 1024;
                if (fileSizeKB > (imageConfig?.maxUploadSizeKB ?? 1024 * 5)) {
                    // 5MB limit by default
                    editorStore.applicationStore.notificationService.notifyError(`File size must be less than ${imageConfig?.maxUploadSizeKB ?? 1024 * 5}KB`);
                    return;
                }
                const compressedImage = await compressImage(file, imageConfig?.maxSizeKB ?? 128, imageConfig?.maxDimension ?? 800);
                const dataProductEmbeddedImageIcon = new DataProductEmbeddedImageIcon(compressedImage);
                dataProduct_setIcon(dataProduct, dataProductEmbeddedImageIcon);
            }
            catch {
                editorStore.applicationStore.notificationService.notifyError('Failed to process image. Please try a different file.');
            }
        }
    };
    return (_jsxs("div", { children: [_jsx("div", { className: "panel__content__form__section__header__prompt", children: "Upload an image to represent this Data Product in the marketplace." }), _jsxs("div", { className: "data-product-editor__image-selector__container", children: [_jsx("input", { id: "data-product-image-upload", name: "data-product-image-upload", type: "file", accept: "image/*", disabled: isReadOnly, onChange: (event) => {
                            // eslint-disable-next-line no-void
                            void handleFileChange(event);
                        }, className: "data-product-editor__image-selector__input", value: dataProduct.icon instanceof DataProductEmbeddedImageIcon
                            ? ''
                            : undefined, ref: imageInputRef }), _jsxs("button", { onClick: () => imageInputRef.current?.click(), className: "data-product-editor__image-selector__upload-btn btn btn--dark", children: [_jsx(UploadIcon, {}), " Upload File"] }), _jsxs("div", { className: "data-product-editor__image-selector__hint", children: ["Supported formats: PNG, JPG, JPEG, GIF (max", ' ', (imageConfig?.maxUploadSizeKB ?? 1024 * 5) / 1024, "MB)"] })] })] }));
});
const DataProductIconEditor = observer((props) => {
    const { product, isReadOnly } = props;
    return (_jsxs("div", { className: "panel__content__form__section data-product-editor__icon-editor", children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Icon/Image" }), _jsx(IconPreviewComponent, { dataProduct: product }), _jsx(IconSelectorComponent, { dataProduct: product, isReadOnly: isReadOnly }), _jsx("div", { className: "panel__content__form__section__header__prompt", style: { marginBottom: 0 }, children: _jsx("b", { children: "or" }) }), _jsx(ImageSelectorComponent, { dataProduct: product, isReadOnly: isReadOnly })] }));
});
const HomeTab = observer((props) => {
    const { dataProductEditorState, isReadOnly } = props;
    const product = dataProductEditorState.product;
    const updateDataProductTitle = (val) => {
        dataProduct_setTitle(product, val ?? '');
    };
    const updateDataProductDescription = (event) => {
        dataProduct_setDescription(product, event.target.value);
    };
    const DATA_PRODUCT_TYPE_OPTIONS = [
        { label: DATA_PRODUCT_TYPE.INTERNAL, value: DATA_PRODUCT_TYPE.INTERNAL },
        { label: DATA_PRODUCT_TYPE.EXTERNAL, value: DATA_PRODUCT_TYPE.EXTERNAL },
    ];
    const handleDataProductTypeChange = action((val) => {
        if (val?.value === DATA_PRODUCT_TYPE.INTERNAL) {
            dataProduct_setType(product, new InternalDataProductType());
        }
        else if (val?.value === DATA_PRODUCT_TYPE.EXTERNAL) {
            const externalType = new ExternalDataProductType();
            const externalLink = observer_DataProductLink(new DataProductLink(''));
            externalType.link = externalLink;
            dataProduct_setType(product, externalType);
        }
    });
    const handleExternalURLChange = (event) => {
        if (product.type instanceof ExternalDataProductType &&
            event.target.value) {
            externalType_setLinkURL(product.type, event.target.value);
        }
    };
    const handleExternalLabelChange = (event) => {
        if (product.type instanceof ExternalDataProductType) {
            externalType_setLinkLabel(product.type, event.target.value);
        }
    };
    return (_jsx("div", { className: "panel__content", children: _jsxs("div", { className: "data-product-editor__home-tab", children: [_jsx(PanelFormTextField, { name: "Title", value: product.title, prompt: "Provide a descriptive name for the Data Product to appear in Marketplace.", update: updateDataProductTitle, placeholder: "Enter title", hasError: product.title === '' || product.title === undefined, errorClassName: "data-product-editor__textbox-error" }), _jsxs("div", { className: "panel__content__form__section", children: [_jsx("div", { className: "panel__content__form__section__header__label", style: { justifyContent: 'space-between', width: '45rem' }, children: "Description" }), _jsx("div", { className: "panel__content__form__section__header__prompt", style: {
                                color: product.description === '' ||
                                    product.description === undefined
                                    ? 'var(--color-red-300)'
                                    : 'var(--color-light-grey-400)',
                                width: '45rem',
                            }, children: "Clearly describe the purpose, content, and intended use of the Data Product. Markdown is supported." }), _jsx("textarea", { className: "panel__content__form__section__textarea", spellCheck: false, disabled: isReadOnly, value: product.description, onChange: updateDataProductDescription, style: {
                                padding: '0.5rem',
                                width: '45rem',
                                height: '10rem',
                                borderColor: product.description === '' ||
                                    product.description === undefined
                                    ? 'var(--color-red-300)'
                                    : 'transparent',
                                resize: 'vertical',
                                maxHeight: '100%',
                                maxWidth: '100%',
                            } })] }), _jsxs("div", { className: "panel__content__form__section", children: [_jsx("div", { className: "panel__content__form__section__header__label", style: { justifyContent: 'space-between', width: '45rem' }, children: "Data Product Type" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Select if this Data Product is Internal or External" }), _jsx("div", { className: "panel__content__form__section__list__new-item__input", children: _jsx(CustomSelectorInput, { options: DATA_PRODUCT_TYPE_OPTIONS, onChange: handleDataProductTypeChange, value: product.type instanceof InternalDataProductType
                                    ? DATA_PRODUCT_TYPE_OPTIONS.find((option) => option.value === DATA_PRODUCT_TYPE.INTERNAL)
                                    : product.type instanceof ExternalDataProductType
                                        ? DATA_PRODUCT_TYPE_OPTIONS.find((option) => option.value === DATA_PRODUCT_TYPE.EXTERNAL)
                                        : null, darkMode: !dataProductEditorState.editorStore.applicationStore
                                    .layoutService.TEMPORARY__isLightColorThemeEnabled }) }), product.type instanceof ExternalDataProductType && (_jsxs("div", { className: "data-product-editor__external-link", children: [_jsx("div", { className: "panel__content__form__section__header__prompt", children: "External Link" }), _jsx("textarea", { className: "input input-group__input panel__content__form__section__input input--dark input--small", spellCheck: false, disabled: isReadOnly, placeholder: "External URL", value: product.type.link.url, onChange: handleExternalURLChange, style: {
                                        resize: 'none',
                                        padding: '0.25rem 0.5rem',
                                    } }), _jsx("textarea", { className: "input input-group__input panel__content__form__section__input input--dark input--small", spellCheck: false, disabled: isReadOnly, placeholder: "External Link Label", value: product.type.link.label ?? '', onChange: handleExternalLabelChange, style: {
                                        resize: 'none',
                                        padding: '0.25rem 0.5rem',
                                    } })] }))] }), _jsx(DataProductIconEditor, { product: product, isReadOnly: isReadOnly })] }) }));
});
const ExpertiseEditor = observer((props) => {
    const { dataProductEditorState } = props;
    const product = dataProductEditorState.product;
    const NewExpertIdComponent = observer((newElementProps) => {
        const { expertise } = newElementProps;
        const [title, setTitle] = useState('');
        return (_jsxs("div", { className: "data-product-editor__support-info__expertise-id-container", children: [_jsx("div", { className: "panel__content__form__section__list__new-item__input", children: _jsx("input", { className: "input input-group__input panel__content__form__section__input input--dark", type: "title", placeholder: "Enter User ID", value: title, onChange: (event) => {
                            setTitle(event.target.value);
                        } }) }), _jsx("button", { className: "panel__content__form__section__list__new-item__add-btn btn btn--dark", onClick: () => {
                        expertise_addId(expertise, title);
                        setTitle('');
                    }, children: "Save" })] }));
    });
    const addNewExpertise = () => {
        dataProductEditorState.createExpertise();
    };
    const updateExpertiseDescription = (expertise, val) => {
        if (val) {
            expertise_setDescription(expertise, val);
        }
    };
    const handleRemoveId = (expertise, id) => {
        expertise_deleteId(expertise, id);
    };
    const handleRemoveExpertise = (expertise) => {
        if (product.supportInfo) {
            supportInfo_deleteExpertise(product.supportInfo, expertise);
        }
    };
    return (_jsxs(_Fragment, { children: [_jsxs(PanelHeader, { className: "panel__header--access-point", children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Expertise" }), _jsx(PanelHeaderActions, { children: _jsx(PanelHeaderActionItem, { className: "panel__header__action", onClick: addNewExpertise, title: "Add new expertise", children: _jsx(PlusIcon, {}) }) })] }), dataProductEditorState.product.supportInfo?.expertise?.map((expertise) => (_jsx(_Fragment, { children: _jsxs("div", { className: "data-product-editor__expertise", children: [_jsxs("div", { className: "panel__content__form__section", children: [_jsx("div", { className: "panel__content__form__section__header__prompt", children: "Description" }), _jsx("textarea", { className: "panel__content__form__section__textarea", spellCheck: false, disabled: dataProductEditorState.isReadOnly, value: expertise.description ?? '', onChange: (event) => updateExpertiseDescription(expertise, event.target.value), style: {
                                        height: '100%',
                                    } })] }), _jsxs("div", { className: "panel__content__form__section", children: [_jsx("div", { className: "panel__content__form__section__header__prompt", children: "User IDs" }), _jsx("div", { className: "panel__content__form__section__list__id-list", children: expertise.expertIds?.map((id) => (_jsxs("div", { className: "panel__content__form__section__list__item", children: [id, _jsx("button", { className: "panel__content__form__section__list__item__remove-btn", disabled: dataProductEditorState.isReadOnly, onClick: () => handleRemoveId(expertise, id), tabIndex: -1, children: _jsx(TimesIcon, {}) })] }, id))) }), _jsx(NewExpertIdComponent, { expertise: expertise })] }), _jsx("div", { className: "data-product-editor__expertise__actions", children: _jsx("button", { className: "access-point-editor__generic-entry__remove-btn--group", onClick: () => {
                                    handleRemoveExpertise(expertise);
                                }, tabIndex: -1, title: "Remove Expertise", children: _jsx(TimesIcon, {}) }) })] }) })))] }));
});
const SupportTab = observer((props) => {
    const { dataProductEditorState, isReadOnly } = props;
    const product = dataProductEditorState.product;
    const updateSupportInfoDocumentationUrl = (val) => {
        dataProduct_setSupportInfoIfAbsent(product);
        if (product.supportInfo) {
            supportInfo_setDocumentationUrl(product.supportInfo, val ?? '');
        }
        if (!val) {
            dataProductEditorState.clearSupportInfo();
        }
    };
    const updateSupportInfoDocumentationLabel = (val) => {
        if (product.supportInfo?.documentation) {
            supportInfo_setLinkLabel(product.supportInfo.documentation, val);
        }
    };
    const updateSupportInfoWebsite = (val) => {
        dataProduct_setSupportInfoIfAbsent(product);
        if (product.supportInfo) {
            supportInfo_setWebsite(product.supportInfo, val ?? '');
        }
        if (!val) {
            dataProductEditorState.clearSupportInfo();
        }
    };
    const updateSupportInfoWebsiteLabel = (val) => {
        if (product.supportInfo?.website) {
            supportInfo_setLinkLabel(product.supportInfo.website, val);
        }
    };
    const updateSupportInfoFaqUrl = (val) => {
        dataProduct_setSupportInfoIfAbsent(product);
        if (product.supportInfo) {
            supportInfo_setFaqUrl(product.supportInfo, val ?? '');
        }
        if (!val) {
            dataProductEditorState.clearSupportInfo();
        }
    };
    const updateSupportInfoFaqLabel = (val) => {
        if (product.supportInfo?.faqUrl) {
            supportInfo_setLinkLabel(product.supportInfo.faqUrl, val);
        }
    };
    const updateSupportInfoSupportUrl = (val) => {
        dataProduct_setSupportInfoIfAbsent(product);
        if (product.supportInfo) {
            supportInfo_setSupportUrl(product.supportInfo, val ?? '');
        }
        if (!val) {
            dataProductEditorState.clearSupportInfo();
        }
        const supportLabelOptions = ['Keystone', 'Jira', 'ServiceNow'];
        supportLabelOptions.forEach((derivedLabel) => {
            if (val?.includes(derivedLabel.toLowerCase()) &&
                product.supportInfo?.supportUrl) {
                supportInfo_setLinkLabel(product.supportInfo.supportUrl, derivedLabel);
            }
        });
    };
    const updateSupportInfoSupportLabel = (val) => {
        if (product.supportInfo?.supportUrl) {
            supportInfo_setLinkLabel(product.supportInfo.supportUrl, val);
        }
    };
    const handleSupportInfoEmailAdd = (address, title) => {
        dataProduct_setSupportInfoIfAbsent(product);
        if (product.supportInfo) {
            supportInfo_addEmail(product.supportInfo, new Email(address, title));
        }
    };
    const handleSupportInfoEmailRemove = (email) => {
        if (product.supportInfo) {
            supportInfo_deleteEmail(product.supportInfo, email);
        }
        if (product.supportInfo?.emails.length === 0) {
            dataProductEditorState.clearSupportInfo();
        }
    };
    const SupportEmailComponent = observer((supportEmailProps) => {
        const { item } = supportEmailProps;
        return (_jsxs("div", { className: "panel__content__form__section__list__item__rows", children: [_jsxs("div", { className: "row", children: [_jsx("label", { className: "label", children: "Address" }), _jsx("div", { className: "textbox", children: item.address })] }), _jsxs("div", { className: "row", children: [_jsx("label", { className: "label", children: "Title" }), _jsx("div", { className: "textbox", children: item.title })] })] }));
    });
    const NewSupportEmailComponent = observer((newSupportEmailProps) => {
        const { onFinishEditing } = newSupportEmailProps;
        const [address, setAddress] = useState('');
        const [title, setTitle] = useState('');
        return (_jsxs("div", { className: "data-product-editor__support-info__new-email", children: [_jsx("div", { className: "panel__content__form__section__list__new-item__input", children: _jsx("input", { className: "input input-group__input panel__content__form__section__input input--dark", type: "email", placeholder: "Enter email", value: address, onChange: (event) => {
                            setAddress(event.target.value);
                        } }) }), _jsx("div", { className: "panel__content__form__section__list__new-item__input", children: _jsx("input", { className: "input input-group__input panel__content__form__section__input input--dark", type: "title", placeholder: "Enter title", value: title, onChange: (event) => {
                            setTitle(event.target.value);
                        } }) }), _jsx("button", { className: "panel__content__form__section__list__new-item__add-btn btn btn--dark", onClick: () => {
                        handleSupportInfoEmailAdd(address, title);
                        setAddress('');
                        setTitle('');
                        onFinishEditing();
                    }, children: "Save" })] }));
    });
    return (_jsxs("div", { className: "data-product-editor__support-info", children: [_jsx("div", { className: "panel__content__form__section__header__label", children: "Support Information" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Configure support information for this Lakehouse Data Product." }), _jsxs("div", { className: "data-product-editor__support-info__link-container", children: [_jsx(PanelFormTextField, { className: "data-product-editor__support-info__input", name: "Documentation", prompt: "URL", value: product.supportInfo?.documentation?.url ?? '', update: updateSupportInfoDocumentationUrl, placeholder: "Documentation URL" }), _jsx(PanelFormTextField, { className: "data-product-editor__support-info__input", name: "", prompt: "Label", isReadOnly: !Boolean(product.supportInfo?.documentation), value: product.supportInfo?.documentation?.label ?? '', update: updateSupportInfoDocumentationLabel, placeholder: "Documentation Label" })] }), _jsxs("div", { className: "data-product-editor__support-info__link-container", children: [_jsx(PanelFormTextField, { name: "Website", prompt: "URL", value: product.supportInfo?.website?.url ?? '', update: updateSupportInfoWebsite, placeholder: "Website URL" }), _jsx(PanelFormTextField, { name: "", prompt: "Label", isReadOnly: !Boolean(product.supportInfo?.website), value: product.supportInfo?.website?.label ?? '', update: updateSupportInfoWebsiteLabel, placeholder: "Website Label" })] }), _jsxs("div", { className: "data-product-editor__support-info__link-container", children: [_jsx(PanelFormTextField, { name: "FAQ", prompt: "URL", value: product.supportInfo?.faqUrl?.url, update: updateSupportInfoFaqUrl, placeholder: "FAQ URL" }), _jsx(PanelFormTextField, { name: "", prompt: "Label", isReadOnly: !Boolean(product.supportInfo?.faqUrl), value: product.supportInfo?.faqUrl?.label, update: updateSupportInfoFaqLabel, placeholder: "FAQ Label" })] }), _jsxs("div", { className: "data-product-editor__support-info__link-container", children: [_jsx(PanelFormTextField, { name: "Support", prompt: "URL", value: product.supportInfo?.supportUrl?.url ?? '', update: updateSupportInfoSupportUrl, placeholder: "Support URL" }), _jsx(PanelFormTextField, { name: "", prompt: "Label", isReadOnly: !Boolean(product.supportInfo?.supportUrl), value: product.supportInfo?.supportUrl?.label, update: updateSupportInfoSupportLabel, placeholder: "Support Label" })] }), _jsx(ListEditor, { title: "Emails", items: product.supportInfo?.emails, keySelector: (email) => email.address + email.title, ItemComponent: SupportEmailComponent, NewItemComponent: NewSupportEmailComponent, handleRemoveItem: handleSupportInfoEmailRemove, isReadOnly: isReadOnly, emptyMessage: "No emails specified" }), _jsx(ExpertiseEditor, { dataProductEditorState: dataProductEditorState })] }));
});
const getDataProductViewerState = (product, graphManagerState, applicationStore, depotServerClient) => {
    const graphManager = guaranteeType(graphManagerState.graphManager, V1_PureGraphManager);
    const v1_dataProduct = guaranteeType(graphManager.elementToProtocol(product), V1_DataProduct);
    const remoteEngine = guaranteeType(graphManager.engine, V1_RemoteEngine);
    let userSearchService = undefined;
    if (applicationStore.pluginManager.getUserPlugins().length > 0) {
        applicationStore.pluginManager
            .getUserPlugins()
            .forEach((plugin) => plugin.setup(applicationStore.config.options.userSearchConfig
            ?.applicationDirectoryUrl));
        userSearchService = new UserSearchService({
            userProfileImageUrl: applicationStore.config.options.userSearchConfig?.userProfileImageUrl,
            applicationDirectoryUrl: applicationStore.config.options.userSearchConfig
                ?.applicationDirectoryUrl,
        });
        userSearchService.registerPlugins(applicationStore.pluginManager.getUserPlugins());
    }
    const dataProductViewerState = new DataProductViewerState(v1_dataProduct, applicationStore, remoteEngine.getEngineServerClient(), depotServerClient, graphManagerState, applicationStore.config.options.dataProductConfig, userSearchService, undefined, {});
    dataProductViewerState.init();
    return dataProductViewerState;
};
const OperationalTab = observer((props) => {
    const { dataProductEditorState, isReadOnly } = props;
    const product = dataProductEditorState.product;
    const CHOOSE_REGION = 'Add Coverage Region...';
    const getCoverageRegionOptions = () => {
        const existingRegions = product.operationalMetadata?.coverageRegions ?? [];
        return Object.values(DataProduct_Region)
            .filter((region) => !existingRegions.includes(region))
            .map((region) => ({
            label: region,
            value: region,
        }));
    };
    const handleAddRegion = (val) => {
        dataProduct_setOperationalMetadataIfAbsent(product);
        if (product.operationalMetadata && val) {
            operationalMetadata_addCoverageRegion(product.operationalMetadata, val.value);
        }
    };
    const handleRemoveRegion = (region) => {
        if (product.operationalMetadata) {
            operationalMetadata_deleteCoverageRegion(product.operationalMetadata, region);
        }
    };
    const handleUpdateFrequencyChange = (val) => {
        dataProduct_setOperationalMetadataIfAbsent(product);
        if (product.operationalMetadata && val) {
            operationalMetadata_setUpdateFrequency(product.operationalMetadata, val.value);
        }
    };
    return (_jsxs("div", { children: [_jsx("div", { className: "panel__content__form__section__header__label", style: { paddingLeft: '1rem' }, children: "Operational Metadata" }), _jsx("div", { className: "panel__content__form__section__header__prompt", style: { paddingLeft: '1rem' }, children: "Configure operational metadata for this Data Product." }), _jsxs("div", { className: "data-product-editor__operational-input", children: [_jsx("div", { className: "panel__content__form__section__header__label", style: { justifyContent: 'space-between', width: '45rem' }, children: "Coverage Regions" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Select the regions this Data Product covers." }), _jsx("div", { className: "panel__content__form__section__list__id-list", children: product.operationalMetadata?.coverageRegions?.map((region) => (_jsxs("div", { className: "panel__content__form__section__list__item", children: [region, _jsx("button", { className: "panel__content__form__section__list__item__remove-btn", disabled: dataProductEditorState.isReadOnly, onClick: () => handleRemoveRegion(region), tabIndex: -1, title: "Remove Region", children: _jsx(TimesIcon, {}) })] }, region))) }), _jsx("div", { className: "panel__content__form__section__list__new-item__input", children: _jsx(CustomSelectorInput, { options: getCoverageRegionOptions(), onChange: handleAddRegion, placeholder: CHOOSE_REGION, darkMode: true, disabled: isReadOnly }) })] }), _jsxs("div", { className: "data-product-editor__operational-input", children: [_jsx("div", { className: "panel__content__form__section__header__label", style: { justifyContent: 'space-between', width: '45rem' }, children: "Update Frequency" }), _jsx("div", { className: "panel__content__form__section__header__prompt", children: "Select the update frequency of this Data Product." }), _jsx("div", { className: "panel__content__form__section__list__new-item__input", children: _jsx(CustomSelectorInput, { options: Object.values(DataProduct_DeliveryFrequency).map((region) => ({
                                label: region,
                                value: region,
                            })), onChange: handleUpdateFrequencyChange, value: product.operationalMetadata?.updateFrequency
                                ? {
                                    label: product.operationalMetadata.updateFrequency,
                                    value: product.operationalMetadata.updateFrequency,
                                }
                                : null, placeholder: "Select update frequency...", darkMode: true, disabled: isReadOnly }) })] })] }));
});
export const DataProductEditor = observer(() => {
    const editorStore = useEditorStore();
    const dataProductEditorState = editorStore.tabManagerState.getCurrentEditorState(DataProductEditorState);
    const product = dataProductEditorState.product;
    const isReadOnly = dataProductEditorState.isReadOnly;
    const auth = useAuth();
    const [showPreview, setShowPreview] = useState(false);
    const [dataProductViewerState, setDataProductViewerState] = useState();
    const deployDataProduct = () => {
        // Trigger OAuth flow if not authenticated
        if (!auth.isAuthenticated) {
            // remove this redirect if we move to do oauth at the beginning of opening studio
            auth
                .signinRedirect({
                state: generateUrlToDeployOnOpen(dataProductEditorState),
            })
                .catch(editorStore.applicationStore.alertUnhandledError);
            return;
        }
        // Use the token for deployment
        const token = auth.user?.access_token;
        if (token) {
            flowResult(dataProductEditorState.deploy(token)).catch(editorStore.applicationStore.alertUnhandledError);
        }
        else {
            editorStore.applicationStore.notificationService.notifyError('Authentication failed. No token available.');
        }
    };
    const selectedActivity = dataProductEditorState.selectedTab;
    const renderActivivtyBarTab = () => {
        switch (selectedActivity) {
            case DATA_PRODUCT_TAB.HOME:
                return (_jsx(HomeTab, { dataProductEditorState: dataProductEditorState, isReadOnly: isReadOnly }));
            case DATA_PRODUCT_TAB.SUPPORT:
                return (_jsx(SupportTab, { dataProductEditorState: dataProductEditorState, isReadOnly: isReadOnly }));
            case DATA_PRODUCT_TAB.APG:
                return (_jsx(AccessPointGroupTab, { dataProductEditorState: dataProductEditorState, isReadOnly: isReadOnly }));
            case DATA_PRODUCT_TAB.OPERATIONAL:
                return (_jsx(OperationalTab, { dataProductEditorState: dataProductEditorState, isReadOnly: isReadOnly }));
            default:
                return null;
        }
    };
    useApplicationNavigationContext(LEGEND_STUDIO_APPLICATION_NAVIGATION_CONTEXT_KEY.DATA_PRODUCT_EDITOR);
    useEffect(() => {
        flowResult(dataProductEditorState.convertAccessPointsFuncObjects()).catch(dataProductEditorState.editorStore.applicationStore.alertUnhandledError);
    }, [dataProductEditorState]);
    useEffect(() => {
        if (dataProductEditorState.deployOnOpen) {
            flowResult(dataProductEditorState.deploy(auth.user?.access_token)).catch(editorStore.applicationStore.alertUnhandledError);
        }
    }, [
        auth,
        editorStore.applicationStore.alertUnhandledError,
        dataProductEditorState,
    ]);
    useEffect(() => autorun(() => {
        if (showPreview) {
            setDataProductViewerState(getDataProductViewerState(product, editorStore.graphManagerState, editorStore.applicationStore, editorStore.depotServerClient));
        }
    }, { delay: 1000 }), [
        editorStore.applicationStore,
        editorStore.graphManagerState,
        editorStore.depotServerClient,
        product,
        showPreview,
    ]);
    return (_jsx("div", { className: "data-product-editor", children: _jsxs("div", { className: "panel", children: [_jsxs("div", { className: "panel__header", children: [_jsxs("div", { className: "panel__header__title", children: [isReadOnly && (_jsx("div", { className: "uml-element-editor__header__lock", children: _jsx(LockIcon, {}) })), _jsx("div", { className: "panel__header__title__label", children: "data product" })] }), _jsxs(PanelHeaderActions, { children: [_jsx("div", { className: "btn__dropdown-combo btn__dropdown-combo--primary", children: _jsx("button", { className: "btn__dropdown-combo__label", onClick: () => {
                                            setShowPreview((prev) => {
                                                if (!prev) {
                                                    setDataProductViewerState(getDataProductViewerState(product, editorStore.graphManagerState, editorStore.applicationStore, editorStore.depotServerClient));
                                                }
                                                return !prev;
                                            });
                                        }, title: showPreview ? 'Hide Preview' : 'Preview Description', tabIndex: -1, style: {
                                            width: '12rem',
                                            justifyContent: 'center',
                                        }, children: showPreview ? (_jsxs(_Fragment, { children: [_jsx(CloseEyeIcon, { className: "btn__dropdown-combo__label__icon" }), _jsx("div", { className: "btn__dropdown-combo__label__title", children: "Hide Preview" })] })) : (_jsxs(_Fragment, { children: [_jsx(EyeIcon, { className: "btn__dropdown-combo__label__icon" }), _jsx("div", { className: "btn__dropdown-combo__label__title", children: "Preview" })] })) }) }), _jsx("div", { className: "btn__dropdown-combo btn__dropdown-combo--primary", children: _jsxs("button", { className: "btn__dropdown-combo__label", onClick: deployDataProduct, title: dataProductEditorState.deployValidationMessage, tabIndex: -1, disabled: !dataProductEditorState.deployValidationMessage, children: [_jsx(RocketIcon, { className: "btn__dropdown-combo__label__icon" }), _jsx("div", { className: "btn__dropdown-combo__label__title", children: "Deploy" })] }) })] })] }), _jsxs("div", { className: "panel", style: { padding: '1rem', flexDirection: 'row' }, children: [_jsx(DataProductSidebar, { dataProductEditorState: dataProductEditorState }), _jsxs(ResizablePanelGroup, { orientation: "vertical", children: [_jsx(ResizablePanel, { children: renderActivivtyBarTab() }), showPreview && dataProductViewerState && (_jsx(ResizablePanelSplitter, {})), showPreview && dataProductViewerState && (_jsx(ResizablePanel, { children: _jsx("div", { className: "data-product-editor__preview-container theme__hc-light", children: _jsx(ProductViewer, { productViewerState: dataProductViewerState }) }) }))] })] })] }) }));
});
//# sourceMappingURL=DataProductEditor.js.map