import { platformSelect } from "@applicaster/zapp-react-native-utils/reactUtils";
import { Observable, from, of } from "rxjs";
import { mergeMap, delay, concatMap } from "rxjs/operators";

const onIdleWeb$ = (x) => {
  return new Observable((subscriber) => {
    // @ts-ignore
    const handlerID = global.requestIdleCallback(() => {
      subscriber.next(x);
      subscriber.complete();
    });

    return () => {
      // @ts-ignore
      global.cancelIdleCallback(handlerID);
    };
  });
};

export const onIdle$ = platformSelect({
  web: onIdleWeb$,
  // TODO - implement idle on other platforms
  default: () => of(undefined),
});

export const forEachSeries$ = (iterable, timeout) => {
  return from(iterable).pipe(
    mergeMap((x) => onIdleWeb$(x)),
    // delay each element by TIMEOUT
    concatMap((x) => of(x).pipe(delay(timeout)))
  );
};
