import { BehaviorSubject, combineLatest } from 'rxjs';
import { useObservable, useObservableEagerState, useRefFn, } from 'observable-hooks';
import { filter, mergeMap, map } from 'rxjs/operators';
import { useCallback } from 'react';
import isPromise from '../../utils/isPromise';
import uniqueId from '../../utils/uniqueId';
export function useObservableBatchedEagerState(input$) {
    var pendingTasksRef = useRefFn(function () { return new Set(); });
    var taskStatusChanges$Ref = useRefFn(function () { return new BehaviorSubject(''); });
    var runInBatchContext = useCallback(function (fn) {
        var taskId = uniqueId('batched-task-');
        var tasks = pendingTasksRef.current;
        var removeTask = function () {
            tasks.delete(taskId);
            taskStatusChanges$Ref.current.next(taskId);
        };
        tasks.add(taskId);
        taskStatusChanges$Ref.current.next(taskId);
        var ret = fn();
        if (isPromise(ret)) {
            ret.then(removeTask, removeTask);
        }
        else {
            removeTask();
        }
    }, [pendingTasksRef, taskStatusChanges$Ref]);
    var observable$ = useObservable(function (args$) {
        return args$.pipe(mergeMap(function (sources$) {
            return combineLatest(sources$).pipe(filter(function (_a) {
                var _ = _a[0], taskId = _a[1];
                return !pendingTasksRef.current.has(taskId);
            }), map(function (_a) {
                var v = _a[0];
                return v;
            }));
        }));
    }, [input$, taskStatusChanges$Ref.current]);
    var value = useObservableEagerState(observable$);
    return [value, runInBatchContext];
}
