import { jsx as _jsx } 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 { BlankPanelContent, clsx } from '@finos/legend-art';
import { useCallback } from 'react';
import { at, isBoolean, isString, parseCSVString, isNonNullable, isNumber, isValidURL, } from '@finos/legend-shared';
import {} from '@finos/legend-graph';
import { DataGrid, } from '@finos/legend-lego/data-grid';
import { getRowDataFromExecutionResult } from '../result/tds/QueryBuilderTDSResultShared.js';
import { getFilterTDSColumnCustomizations } from '../result/tds/QueryBuilderTDSGridResult.js';
const parseExecutionResultData = (data) => {
    const lines = data.split('\n').filter((line) => line.trim().length);
    if (lines.length) {
        const columns = parseCSVString(at(lines, 0)) ?? [];
        const rowData = lines
            .slice(1)
            .map((item) => {
            const rowItems = parseCSVString(item);
            if (!rowItems) {
                return undefined;
            }
            const row = {};
            columns.forEach((column, idx) => {
                row[column] = rowItems[idx] ?? '';
            });
            return row;
        })
            .filter(isNonNullable);
        return { rowData, columns };
    }
    return undefined;
};
const TDSResultCellRenderer = observer((params) => {
    const cellValue = params.value;
    const formattedCellValue = () => {
        if (isNumber(cellValue)) {
            return Intl.NumberFormat('en-US', {
                maximumFractionDigits: 4,
            }).format(Number(cellValue));
        }
        else if (isBoolean(cellValue)) {
            return String(cellValue);
        }
        return cellValue;
    };
    const cellValueUrlLink = isString(cellValue) && isValidURL(cellValue) ? cellValue : undefined;
    return (_jsx("div", { className: clsx('query-builder__result__values__table__cell'), children: cellValueUrlLink ? (_jsx("a", { href: cellValueUrlLink, target: "_blank", rel: "noreferrer", children: cellValueUrlLink })) : (_jsx("span", { children: formattedCellValue() })) }));
});
export const PlayGroundSQLExecutionResultGrid = observer((props) => {
    const { result, useAdvancedGrid, useLocalMode, enableDarkMode = false, } = props;
    const data = parseExecutionResultData(result);
    const darkMode = enableDarkMode;
    if (!data) {
        return (_jsx(BlankPanelContent, { children: `Can't parse result, displaying raw form:\n${result}` }));
    }
    if (useAdvancedGrid) {
        if (useLocalMode) {
            const localcolDefs = data.columns.map((colName) => ({
                minWidth: 150,
                sortable: true,
                resizable: true,
                field: colName,
                flex: 1,
                enablePivot: true,
                enableRowGroup: true,
                enableValue: true,
                allowedAggFuncs: ['count'],
            }));
            return (_jsx("div", { className: clsx('sql-playground__result__grid', {
                    'ag-theme-balham': !darkMode,
                    'ag-theme-balham-dark': darkMode,
                }), children: _jsx(DataGrid, { rowData: data.rowData, gridOptions: {
                        suppressScrollOnNewData: true,
                        rowSelection: {
                            mode: 'multiRow',
                            checkboxes: false,
                            headerCheckbox: false,
                        },
                        pivotPanelShow: 'always',
                        rowGroupPanelShow: 'always',
                        cellSelection: true,
                    }, 
                    // NOTE: when column definition changed, we need to force refresh the cell to make sure the cell renderer is updated
                    // See https://stackoverflow.com/questions/56341073/how-to-refresh-an-ag-grid-when-a-change-occurs-inside-a-custom-cell-renderer-com
                    onRowDataUpdated: (params) => {
                        params.api.refreshCells({ force: true });
                    }, suppressFieldDotNotation: true, suppressContextMenu: false, columnDefs: localcolDefs, sideBar: ['columns', 'filters'] }) }));
        }
        const colDefs = data.columns.map((colName) => ({
            minWidth: 150,
            sortable: true,
            resizable: true,
            field: colName,
            flex: 1,
            cellRenderer: TDSResultCellRenderer,
            filter: true,
        }));
        const getContextMenuItems = useCallback((params) => [
            'copy',
            'copyWithHeaders',
            {
                name: 'Copy Row Value',
                action: () => {
                    params.api.copySelectedRowsToClipboard();
                },
            },
        ], []);
        return (_jsx("div", { className: clsx('sql-playground__result__grid', {
                'ag-theme-balham': !darkMode,
                'ag-theme-balham-dark': darkMode,
            }), children: _jsx(DataGrid, { rowData: data.rowData, overlayNoRowsTemplate: `<div class="sql-playground__result__grid--empty">No results</div>`, gridOptions: {
                    suppressScrollOnNewData: true,
                    rowSelection: {
                        mode: 'multiRow',
                        checkboxes: false,
                        headerCheckbox: false,
                    },
                    cellSelection: true,
                }, onRowDataUpdated: (params) => {
                    params.api.refreshCells({ force: true });
                }, suppressFieldDotNotation: true, suppressClipboardPaste: false, suppressContextMenu: false, columnDefs: colDefs, getContextMenuItems: (params) => getContextMenuItems(params) }) }));
    }
    return (_jsx("div", { className: clsx('sql-playground__result__grid', {
            'ag-theme-balham': !darkMode,
            'ag-theme-balham-dark': darkMode,
        }), children: _jsx(DataGrid, { rowData: data.rowData, overlayNoRowsTemplate: `<div class="sql-playground__result__grid--empty">No results</div>`, alwaysShowVerticalScroll: true, suppressFieldDotNotation: true, columnDefs: data.columns.map((column) => ({
                minWidth: 150,
                sortable: true,
                resizable: true,
                headerName: column,
                field: column,
                flex: 1,
            })) }) }));
});
// NOTE: TEMPORARY - this component will be removed and replaced with QueryBuilderTDSGridResult
// once the dependency on QueryBuilderState is removed from that component.
export const TEMPORARY_PlaygroundTDSResultGrid = observer((props) => {
    const { result, useAdvancedGrid, useLocalMode, enableDarkMode = false, } = props;
    const rowData = getRowDataFromExecutionResult(result);
    const darkMode = enableDarkMode;
    const getContextMenuItems = useCallback((params) => [
        'copy',
        'copyWithHeaders',
        {
            name: 'Copy Row Value',
            action: () => {
                params.api.copySelectedRowsToClipboard();
            },
        },
    ], []);
    if (useAdvancedGrid && useLocalMode) {
        const localColDefs = result.result.columns.map((colName) => ({
            minWidth: 150,
            sortable: true,
            resizable: true,
            field: colName,
            flex: 1,
            enablePivot: true,
            enableRowGroup: true,
            enableValue: true,
            cellRenderer: TDSResultCellRenderer,
            allowedAggFuncs: ['count'],
        }));
        return (_jsx("div", { className: clsx('sql-playground__result__grid', {
                'ag-theme-balham': !darkMode,
                'ag-theme-balham-dark': darkMode,
            }), children: _jsx(DataGrid, { rowData: rowData, gridOptions: {
                    suppressScrollOnNewData: true,
                    getRowId: (data) => `${data.data.rowNumber}`,
                    rowSelection: {
                        mode: 'multiRow',
                        checkboxes: false,
                        headerCheckbox: false,
                    },
                    pivotPanelShow: 'always',
                    rowGroupPanelShow: 'always',
                    cellSelection: true,
                }, onRowDataUpdated: (params) => {
                    params.api.refreshCells({ force: true });
                }, suppressFieldDotNotation: true, suppressContextMenu: false, columnDefs: localColDefs, sideBar: ['columns', 'filters'], getContextMenuItems: (params) => getContextMenuItems(params) }) }));
    }
    if (useAdvancedGrid) {
        const colDefs = result.result.columns.map((colName) => ({
            minWidth: 150,
            sortable: true,
            resizable: true,
            field: colName,
            flex: 1,
            cellRenderer: TDSResultCellRenderer,
            ...getFilterTDSColumnCustomizations(result, colName),
        }));
        return (_jsx("div", { className: clsx('sql-playground__result__grid', {
                'ag-theme-balham': !darkMode,
                'ag-theme-balham-dark': darkMode,
            }), children: _jsx(DataGrid, { rowData: rowData, overlayNoRowsTemplate: `<div class="sql-playground__result__grid--empty">No results</div>`, gridOptions: {
                    suppressScrollOnNewData: true,
                    getRowId: (data) => `${data.data.rowNumber}`,
                    rowSelection: {
                        mode: 'multiRow',
                        checkboxes: false,
                        headerCheckbox: false,
                    },
                    cellSelection: true,
                }, onRowDataUpdated: (params) => {
                    params.api.refreshCells({ force: true });
                }, suppressFieldDotNotation: true, suppressClipboardPaste: false, suppressContextMenu: false, columnDefs: colDefs, getContextMenuItems: (params) => getContextMenuItems(params) }) }));
    }
    const colDefs = result.result.columns.map((colName) => ({
        minWidth: 150,
        sortable: true,
        resizable: true,
        headerName: colName,
        field: colName,
        flex: 1,
        cellRenderer: TDSResultCellRenderer,
    }));
    return (_jsx("div", { className: clsx('sql-playground__result__grid', {
            'ag-theme-balham': !darkMode,
            'ag-theme-balham-dark': darkMode,
        }), children: _jsx(DataGrid, { rowData: rowData, overlayNoRowsTemplate: `<div class="sql-playground__result__grid--empty">No results</div>`, alwaysShowVerticalScroll: true, suppressFieldDotNotation: true, columnDefs: colDefs }) }));
});
//# sourceMappingURL=SQLPlaygroundGrid.js.map