import { catchError, filter, map, of } from "rxjs";
import { useEffect, useMemo, useState } from "react";
import { createSimpleContext } from "../simple";
// FIXME needs refactor
const Context = createSimpleContext("eq-rxjs-api", undefined, ({ useNet, useBase, updateTimestamp, }) => {
    const { api: eqApi } = useBase();
    const { network } = useNet();
    const [value, setValue] = useState();
    const _api = useMemo(() => {
        if (eqApi && network?.type) {
            // TODO do not use api creator; refactor to ApiRx.create
            const api$ = eqApi
                .getApiCreatorRx(network.type)(network.node)
                .pipe(catchError((e) => of(undefined)), filter((v) => !!v));
            const apiRx$ = api$.pipe(map((api) => api._api));
            return { api$, apiRx$ };
        }
    }, [eqApi, network]);
    useEffect(() => {
        let disconnect;
        const sub = _api?.api$.subscribe((api) => {
            disconnect = api._api.disconnect.bind(api._api);
            setValue(Object.assign(api, { api$: _api.api$, apiRx$: _api.apiRx$ }));
        });
        return () => {
            // disconnect?.();
            // sub?.unsubscribe();
        };
    }, [_api, updateTimestamp]);
    return value;
});
export const ApiProvider = Context.Provider;
// @ts-expect-error
export const useApi = Context.useContext;
//# sourceMappingURL=api.js.map