import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * Copyright (c) 2020-present, Goldman Sachs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { useApplicationStore } from '@finos/legend-application';
import { CheckCircleIcon, ExclamationCircleIcon, MinusCircleIcon, PanelLoadingIndicator, RefreshIcon, TimesCircleIcon, clsx, } from '@finos/legend-art';
import { DataGrid, } from '@finos/legend-lego/data-grid';
import { DatasetEntitlementAccessApprovedReport, DatasetEntitlementAccessGrantedReport, DatasetEntitlementAccessNotGrantedReport, DatasetEntitlementAccessRequestedReport, DatasetEntitlementUnsupportedReport, } from '@finos/legend-graph';
import { Chart as ChartJS, DoughnutController, ArcElement } from 'chart.js';
ChartJS.register(DoughnutController, ArcElement);
const DataAccessOverviewChart = observer((props) => {
    const { dataAccessState } = props;
    const canvasRef = useRef(null);
    const chartRef = useRef(null);
    const entitlementCheckInfo = dataAccessState.entitlementCheckInfo;
    const total = entitlementCheckInfo.total;
    const accessGrantedCount = entitlementCheckInfo.data[0]?.count ?? 0;
    const accessGrantedPercentage = entitlementCheckInfo.data[0]?.percentage ?? 0;
    useEffect(() => {
        if (canvasRef.current && !chartRef.current) {
            chartRef.current = new ChartJS(canvasRef.current, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [],
                },
                options: {
                    responsive: true,
                    resizeDelay: 0,
                    maintainAspectRatio: false,
                    cutout: '75%',
                },
            });
        }
        return () => {
            chartRef.current?.destroy();
            chartRef.current = null;
        };
    }, []);
    useEffect(() => {
        if (chartRef.current) {
            chartRef.current.data = {
                labels: entitlementCheckInfo.data.map((item) => item.label),
                datasets: [
                    {
                        data: entitlementCheckInfo.data.map((item) => item.count),
                        backgroundColor: entitlementCheckInfo.data.map((item) => item.color),
                        hoverBorderWidth: 0,
                        borderWidth: 0,
                    },
                ],
            };
            chartRef.current.options = {
                ...chartRef.current.options,
                plugins: {
                    tooltip: {
                        enabled: entitlementCheckInfo.total !== 0,
                        usePointStyle: false,
                        boxPadding: 5,
                        callbacks: {
                            labelPointStyle: () => ({
                                pointStyle: 'rectRounded',
                                rotation: 0,
                            }),
                        },
                    },
                },
            };
            chartRef.current.update('resize');
        }
    }, [entitlementCheckInfo]);
    return (_jsx("div", { className: "data-access-overview__chart", children: _jsxs("div", { className: "data-access-overview__chart__container", children: [_jsx("canvas", { ref: canvasRef }), _jsxs("div", { className: "data-access-overview__chart__stats", children: [_jsxs("div", { className: "data-access-overview__chart__stats__percentage", children: [total === 0 ? 0 : accessGrantedPercentage, "%"] }), _jsxs("div", { className: "data-access-overview__chart__stats__tally", children: [total === 0 ? 0 : accessGrantedCount, "/", total] })] })] }) }));
});
const AccessStatusCellRenderer = observer((params) => {
    const { data, dataAccessState } = params;
    const applicationStore = useApplicationStore();
    if (!data) {
        return null;
    }
    if (data.entitlementReport instanceof DatasetEntitlementAccessGrantedReport) {
        return (_jsx("div", { className: "data-access-overview__grid__access-status-cell", children: _jsxs("div", { className: "data-access-overview__grid__access-status-cell__content", children: [_jsx("div", { className: "data-access-overview__grid__access-status-cell__icon data-access-overview__grid__access-status-cell__icon--access-granted", children: _jsx(CheckCircleIcon, {}) }), _jsx("div", { className: "data-access-overview__grid__access-status-cell__text", children: "Access Granted" })] }) }));
    }
    else if (data.entitlementReport instanceof DatasetEntitlementAccessApprovedReport) {
        return (_jsx("div", { className: "data-access-overview__grid__access-status-cell", children: _jsxs("div", { className: "data-access-overview__grid__access-status-cell__content", children: [_jsx("div", { className: "data-access-overview__grid__access-status-cell__icon data-access-overview__grid__access-status-cell__icon--access-approved", children: _jsx(MinusCircleIcon, {}) }), _jsx("div", { className: "data-access-overview__grid__access-status-cell__text", children: "Access Approved" })] }) }));
    }
    else if (data.entitlementReport instanceof DatasetEntitlementAccessRequestedReport) {
        return (_jsx("div", { className: "data-access-overview__grid__access-status-cell", children: _jsxs("div", { className: "data-access-overview__grid__access-status-cell__content", children: [_jsx("div", { className: "data-access-overview__grid__access-status-cell__icon data-access-overview__grid__access-status-cell__icon--access-requested", children: _jsx(ExclamationCircleIcon, {}) }), _jsx("div", { className: "data-access-overview__grid__access-status-cell__text", children: "Access Requested" })] }) }));
    }
    else if (data.entitlementReport instanceof DatasetEntitlementAccessNotGrantedReport) {
        const plugins = applicationStore.pluginManager
            .getApplicationPlugins()
            .flatMap((plugin) => plugin.getExtraDatasetEntitlementAccessNotGrantedReportActionConfigurations?.() ??
            []);
        let action;
        for (const plugin of plugins) {
            action = plugin.renderer(data, dataAccessState);
            if (action) {
                break;
            }
        }
        return (_jsxs("div", { className: "data-access-overview__grid__access-status-cell", children: [_jsxs("div", { className: "data-access-overview__grid__access-status-cell__content", children: [_jsx("div", { className: "data-access-overview__grid__access-status-cell__icon data-access-overview__grid__access-status-cell__icon--access-not-granted", children: _jsx(TimesCircleIcon, {}) }), _jsx("div", { className: "data-access-overview__grid__access-status-cell__text", children: "Access Not Granted" })] }), action && (_jsx("div", { className: "data-access-overview__grid__access-status-cell__action", children: action }))] }));
    }
    else if (data.entitlementReport instanceof DatasetEntitlementUnsupportedReport) {
        return (_jsx("div", { className: "data-access-overview__grid__empty-cell", children: "(unsupported)" }));
    }
    return null;
});
const DataAccessOverviewGrid = observer((props) => {
    const { dataAccessState } = props;
    const darkMode = !dataAccessState.applicationStore.layoutService
        .TEMPORARY__isLightColorThemeEnabled;
    return (_jsx("div", { className: clsx('data-access-overview__grid', {
            'ag-theme-balham': !darkMode,
            'ag-theme-balham-dark': darkMode,
        }), children: _jsx(DataGrid, { rowData: dataAccessState.datasets, gridOptions: {
                suppressScrollOnNewData: true,
                getRowId: (rowData) => rowData.data.uuid,
            }, columnDefs: [
                {
                    minWidth: 50,
                    sortable: true,
                    resizable: true,
                    field: 'specification.name',
                    headerName: 'Dataset',
                    flex: 1,
                },
                {
                    minWidth: 50,
                    sortable: true,
                    resizable: true,
                    field: 'specification.type',
                    headerName: 'Type',
                    flex: 1,
                },
                {
                    minWidth: 50,
                    sortable: true,
                    resizable: true,
                    headerName: 'Access Status',
                    cellRendererParams: {
                        dataAccessState,
                    },
                    cellRenderer: AccessStatusCellRenderer,
                    flex: 1,
                },
            ] }) }));
});
export const DataAccessOverview = observer((props) => {
    const { dataAccessState, compact } = props;
    const applicationStore = useApplicationStore();
    useEffect(() => {
        // NOTE: @YannanGao-gs - force refresh for now, let's investigate why the data is empty
        // when we fetched it from cache
        dataAccessState.refresh().catch(applicationStore.alertUnhandledError);
        // dataAccessState.intialize().catch(applicationStore.alertUnhandledError);
    }, [applicationStore, dataAccessState]);
    const renderWarehouseEntitlementTab = () => {
        const plugins = applicationStore.pluginManager
            .getApplicationPlugins()
            .flatMap((plugin) => plugin.getWarehouseEntitlementRenders?.() ?? []);
        let warehouseEntitlementRender;
        for (const plugin of plugins) {
            warehouseEntitlementRender = plugin.renderer(dataAccessState);
            if (warehouseEntitlementRender) {
                break;
            }
        }
        return warehouseEntitlementRender;
    };
    const warehouseEntitlementTab = renderWarehouseEntitlementTab();
    return (_jsxs("div", { className: clsx('data-access-overview', {
            'data-access-overview--compact': Boolean(compact),
        }), children: [_jsx(PanelLoadingIndicator, { isLoading: dataAccessState.surveyDatasetsState.isInProgress ||
                    dataAccessState.checkEntitlementsState.isInProgress }), _jsxs("div", { className: "data-access-overview__actions", children: [Boolean(dataAccessState.datasets.find((dataset) => dataset.entitlementReport instanceof
                        DatasetEntitlementUnsupportedReport)) && (_jsx("div", { className: "data-access-overview__actions__warning", children: "Use case is not fully supported!" })), _jsx("button", { className: "data-access-overview__actions__refresh-btn btn--dark", tabIndex: -1, title: "Refresh", onClick: () => {
                            dataAccessState
                                .refresh()
                                .catch(applicationStore.alertUnhandledError);
                        }, children: _jsx(RefreshIcon, {}) })] }), _jsxs("div", { className: "data-access-overview__datasets", children: [_jsx("div", { className: "data-access-overview__header", children: "DATASET ENTITLEMENTS" }), _jsx(DataAccessOverviewChart, { dataAccessState: dataAccessState }), _jsx(DataAccessOverviewGrid, { dataAccessState: dataAccessState })] }), warehouseEntitlementTab] }));
});
//# sourceMappingURL=DataAccessOverview.js.map