//
// Copyright 2024 DXOS.org
//
import React, { useEffect, useState } from 'react';
import { getSyncSummary, useSyncState } from '@dxos/react-client/echo';
import { Icon, Toggle } from '@dxos/react-ui';
import { removeEmpty } from '../../hooks';
import { Panel } from './Panel';
import { DatabasePanel, EdgePanel, LoggingPanel, MemoryPanel, NetworkPanel, PerformancePanel, QueriesPanel, RawQueriesPanel, ReplicatorMessagesPanel, ReplicatorPanel, SpansPanel, SyncStatusPanel, TimeSeries, } from './panels';
const LOCAL_STORAGE_KEY = 'dxos.org/plugin/debug/panels';
const PANEL_KEYS = [
    'ts',
    'performance',
    'spans',
    'edge',
    'queries',
    'rawQueries',
    'database',
    'logging',
    'memory',
    'replicator',
    'replicatorMessages',
    'sync',
];
// TODO(burdon): Reconcile with TraceView in diagnostics.
export const StatsPanel = ({ stats, onRefresh, children }) => {
    const [live, setLive] = useState(false);
    const handleToggleLive = () => setLive((live) => !live);
    useEffect(() => {
        if (live && onRefresh) {
            const interval = setInterval(onRefresh, 5_000);
            return () => clearInterval(interval);
        }
    }, [live, onRefresh]);
    // TODO(burdon): Factor out util.
    const rawQueries = (stats?.queries ?? []).reduce((acc, query) => {
        const raw = removeEmpty(query.filter);
        delete raw.options;
        raw.type = raw.type?.itemId;
        const str = JSON.stringify(raw);
        const num = acc.get(str) ?? 0;
        acc.set(str, num + 1);
        return acc;
    }, new Map());
    const spans = [...(stats?.diagnostics?.spans ?? [])];
    spans.reverse();
    const queries = [...(stats?.queries ?? [])];
    queries.reverse();
    const syncState = useSyncState();
    const syncSummary = getSyncSummary(syncState);
    // Store in local storage.
    const [panelState, setPanelState] = useState(() => PANEL_KEYS.reduce((acc, key) => {
        acc[key] = localStorage?.getItem(`${LOCAL_STORAGE_KEY}/${key}`) === 'true';
        return acc;
    }, {}));
    const handleToggle = (id, open) => {
        setPanelState({ ...panelState, [id]: open });
        localStorage?.setItem(`${LOCAL_STORAGE_KEY}/${id}`, String(open));
    };
    const props = (id) => ({
        id,
        open: panelState[id],
        onToggle: handleToggle,
    });
    return (React.createElement("div", { role: 'none', className: 'flex flex-col is-full bs-full max-bs-[calc(var(--radix-popover-content-available-height)-2*var(--dx-modalLine))] overflow-y-auto divide-y divide-separator' },
        React.createElement(Panel, { id: 'main', icon: 'ph--chart-bar--regular', title: 'Stats', info: React.createElement(Toggle, { pressed: live, classNames: 'p-0 bg-transparent', density: 'fine', value: 'ghost', onClick: handleToggleLive },
                React.createElement(Icon, { icon: live ? 'ph--pause--regular' : 'ph--play--regular', size: 4 })) }),
        React.createElement(LoggingPanel, { ...props('logging') }),
        React.createElement(MemoryPanel, { id: 'memory', memory: stats?.memory }),
        React.createElement(NetworkPanel, { id: 'network', network: stats?.network }),
        React.createElement(EdgePanel, { id: 'edge', open: panelState.edge, edge: stats?.edge, onToggle: handleToggle }),
        React.createElement(PerformancePanel, { id: 'performance', open: panelState.performance, onToggle: handleToggle, entries: stats?.performanceEntries }),
        React.createElement(DatabasePanel, { id: 'database', open: panelState.database, onToggle: handleToggle, database: stats?.database }),
        React.createElement(ReplicatorPanel, { id: 'replicator', open: panelState.replicator, onToggle: handleToggle, database: stats?.database }),
        React.createElement(ReplicatorMessagesPanel, { id: 'replicatorMessages', open: panelState.replicatorMessages, onToggle: handleToggle, database: stats?.database }),
        React.createElement(SpansPanel, { id: 'spans', open: panelState.spans, onToggle: handleToggle, spans: spans }),
        React.createElement(QueriesPanel, { id: 'queries', open: panelState.queries, onToggle: handleToggle, queries: queries }),
        React.createElement(RawQueriesPanel, { id: 'rawQueries', open: panelState.rawQueries, onToggle: handleToggle, queries: rawQueries }),
        React.createElement(SyncStatusPanel, { id: 'sync', open: panelState.sync, onToggle: handleToggle, state: syncState, summary: syncSummary, debug: true }),
        React.createElement(TimeSeries, { id: 'ts', open: panelState.ts, onToggle: handleToggle }),
        children));
};
//# sourceMappingURL=StatsPanel.js.map