import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import {} from '../../api/websocket';
import WebSocketCtx from '../../shared/context/websocket-context';
/**
 * Helper hook to subscribe to errors coming from the backend
 */
function useBackendErrorsSubscription() {
    const [errors, setErrors] = useState([]);
    const { client } = useContext(WebSocketCtx);
    useEffect(() => {
        if (!client) {
            return;
        }
        const sub = client.serverErrors$().subscribe((err) => {
            setErrors((prev) => [...prev, err.message]);
        });
        return () => {
            sub.unsubscribe();
        };
    }, [client]);
    const clearErrors = useCallback(() => {
        setErrors([]);
    }, []);
    return [errors, clearErrors];
}
const BackendErrorsCtx = createContext(null);
/**
 * Provides a live stream of backend errors
 */
export function BackendErrorsProvider(props) {
    const [errors, clearErrors] = useBackendErrorsSubscription();
    return _jsx(BackendErrorsCtx.Provider, { value: { clearErrors, errors }, children: props.children });
}
/**
 * Get the current backend errors from context
 */
export function useBackendErrors() {
    const ctx = useContext(BackendErrorsCtx);
    if (!ctx) {
        throw new Error('useBackendErrors must be used within BackendErrorsProvider');
    }
    return ctx;
}
//# sourceMappingURL=backend-errors-ctx.js.map