//
// Copyright 2020 DXOS.org
//
import * as localForage from 'localforage';
import React from 'react';
import { invariant } from '@dxos/invariant';
import { SpaceId, useSpaces } from '@dxos/react-client/echo';
import { useAsyncEffect } from '@dxos/react-hooks';
import { Select } from '@dxos/react-ui';
import { useDevtoolsDispatch, useDevtoolsState, useSpacesInfo } from '../hooks';
export const DataSpaceSelector = () => {
    const spaces = useSpaces({ all: true });
    const spacesInfo = useSpacesInfo();
    const { space } = useDevtoolsState();
    const setState = useDevtoolsDispatch();
    const handleSelect = (spaceId) => {
        const space = spaceId ? spaces.find((space) => space.id === spaceId) : undefined;
        // TODO(dmaretskyi): Expose id in space info.
        const spaceInfo = space ? spacesInfo.find((spaceInfo) => spaceInfo.key.equals(space.key)) : undefined;
        setState((state) => ({
            ...state,
            space,
            spaceInfo,
        }));
        if (spaceId) {
            void localForage.setItem('dxos.devtools.spaceId', spaceId);
        }
    };
    useAsyncEffect(async () => {
        const spaceId = await localForage.getItem('dxos.devtools.spaceId');
        if (spaceId) {
            invariant(SpaceId.isValid(spaceId));
            handleSelect(spaceId);
        }
    }, []);
    const getLabel = (space) => {
        return space?.isOpen ? (space?.properties.name ?? 'New space') : '(closed)';
    };
    return (React.createElement(Select.Root, { value: space?.id, onValueChange: (id) => {
            id && handleSelect?.(id);
        } },
        React.createElement(Select.TriggerButton, { placeholder: 'Select space' }),
        React.createElement(Select.Portal, null,
            React.createElement(Select.Content, null,
                React.createElement(Select.Viewport, null, spaces.map((space) => (React.createElement(Select.Option, { key: space.id, value: space.id },
                    React.createElement("div", { className: 'flex items-center gap-2' },
                        React.createElement("span", { className: 'font-mono text-neutral-250' }, space.id.slice(0, 6)),
                        getLabel(space)))))),
                React.createElement(Select.Arrow, null)))));
};
//# sourceMappingURL=DataSpaceSelector.js.map