//
// Copyright 2025 DXOS.org
//
import React, { useEffect, useMemo, useState } from 'react';
import { asyncTimeout, scheduleTask } from '@dxos/async';
import { createEdgeIdentity } from '@dxos/client/edge';
import { Context } from '@dxos/context';
import { EdgeStatus as WsStatus } from '@dxos/protocols/proto/dxos/client/services';
import { useClient } from '@dxos/react-client';
import { IconButton } from '@dxos/react-ui';
import { Panel } from '../Panel';
import { Table, Unit } from './Table';
const IDENTITY_WAIT_TIMEOUT = 30_000;
export const EdgePanel = ({ edge, ...props }) => {
    const client = useClient();
    const [edgeStatus, setEdgeStatus] = useState();
    const handleRefresh = async () => {
        const status = await client.edge.getStatus();
        setEdgeStatus(status);
    };
    const handleCopyRaw = async () => {
        await navigator.clipboard.writeText(JSON.stringify(edgeStatus, null, 2));
    };
    useEffect(() => {
        const ctx = new Context();
        scheduleTask(ctx, async () => {
            await asyncTimeout(client.spaces.waitUntilReady(), IDENTITY_WAIT_TIMEOUT);
            client.edge.setIdentity(createEdgeIdentity(client));
            await handleRefresh();
        });
        return () => {
            void ctx.dispose();
        };
    }, []);
    const rows = useMemo(() => getHealthReportTable(edgeStatus, edge?.status), [edgeStatus, edge?.status]);
    return (React.createElement(Panel, { ...props, icon: 'ph--cloud--regular', title: 'EDGE', info: React.createElement("div", { className: 'flex items-center gap-2' },
            " ",
            edgeStatus?.problems.length === 0 ? '✅' : '❌'), maxHeight: 0 },
        React.createElement("div", { className: 'flex flex-col is-full gap-2 text-xs' },
            React.createElement("div", { className: 'flex items-center gap-2' },
                React.createElement(IconButton, { icon: 'ph--arrow-clockwise--regular', label: 'refresh', onClick: handleRefresh }),
                React.createElement(IconButton, { icon: 'ph--copy--regular', label: 'copy raw', onClick: handleCopyRaw })),
            React.createElement(Table, { rows: rows }),
            (edgeStatus?.problems?.length ?? 0) > 0 && (React.createElement("div", { className: 'flex flex-col pli-2' },
                React.createElement("span", null, "Issues"),
                React.createElement("ol", { className: 'pli-2 list-decimal' }, edgeStatus?.problems?.map((problem, idx) => (React.createElement("li", { key: idx, className: 'text-description' }, problem)))))))));
};
const getHealthReportTable = (status, wsStatus) => {
    const isConnected = wsStatus?.state === WsStatus.ConnectionState.CONNECTED;
    const rows = [
        [isConnected ? '✅' : '❌', 'web socket', isConnected ? 'Connected' : 'Disconnected'],
        ...(!isConnected
            ? []
            : [
                ['', 'uptime', wsStatus?.uptime?.toFixed(0) ?? 'N/A', 's'],
                ['', 'RTT', wsStatus?.rtt?.toFixed(0) ?? 'N/A', 'ms'],
                ['', 'up', Unit.KB(wsStatus?.rateBytesUp ?? 0), 'KB/s'],
                ['', 'down', Unit.KB(wsStatus?.rateBytesDown ?? 0), 'KB/s'],
            ]),
    ];
    if (!status) {
        return rows;
    }
    rows.push([
        (status.router.connectedDevices?.length ?? 0) > 0 && !status.router.fetchError ? '✅' : '❌',
        'router',
        `Devices: ${status.router.connectedDevices?.length ?? 0}`,
    ], [status.agent.agentStatus === 'active' ? '✅' : '❌', 'agent', status.agent.agentStatus ?? ''], [!status.spaces.fetchError ? '✅' : '❌', 'spaces', `Spaces: ${Object.keys(status.spaces.data ?? {}).length ?? 0}`], ...Object.entries(status.spaces.data ?? {}).map(([spaceId, space]) => [
        space.diagnostics?.redFlags?.length > 0 || space.fetchError ? '❌' : '✅',
        spaceId,
    ]));
    return rows;
};
//# sourceMappingURL=EdgePanel.js.map